PDF.PDF.java Source code

Java tutorial

Introduction

Here is the source code for PDF.PDF.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package PDF;

import com.itextpdf.text.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

/**
 *
 * @author USER
 */
public class PDF {

    /**
     *
     * This is assigning some default values into the variables
     */
    private String filename;
    private File f;

    /**
     *
     * @param fname this is the filename passed in from the jsp
     * @param k this is all the details from the order to be passed to pdf
     * @exception FileNotFoundException this will catch an error if the file to
     * be or written to is not found OutputStream file outputs the given file to
     * bytes PdfWriter writer creates a pdf version of the given file (file) to
     * the given format (doc) HTMLWorker htmlWorker converts the data from the
     * String (k) to the PDF format doc.close() closes access the document
     * file.close() closes access to the file
        
     */
    public PDF(String fname, String k) throws FileNotFoundException {
        filename = "Order" + fname + ".pdf";
        try {
            f = new File(filename);
            OutputStream file = new FileOutputStream(f);
            Document doc = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(doc, file);
            doc.open();
            HTMLWorker htmlWorker = new HTMLWorker(doc);
            htmlWorker.parse(new StringReader(k));
            doc.close();
            file.close();
        } catch (IOException | DocumentException e) {
            System.err.println("IOExcetpion");
        }
    }

    /**
     * Method to return the absolute path of the file
     *
     * @return type String the absolute path of f
     */
    public String getPath() {
        return f.getAbsolutePath();
    }

    /**
     * Method to return the file
     *
     * @return type File f
     */
    public File getFile() {
        return f;
    }

    /**
     * Method to return the filename
     *
     * @return type String the filename
     */
    public String getFilename() {
        return filename;
    }
}