smsapp.utils.WriteSMSToDocFile.java Source code

Java tutorial

Introduction

Here is the source code for smsapp.utils.WriteSMSToDocFile.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 smsapp.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import smsapp.models.ModelSmsApp;

/**
 *
 * @author S.Karanja
 */
public class WriteSMSToDocFile {

    private FileOutputStream os;
    private XWPFDocument doc;
    private XWPFParagraph para;
    private XWPFRun paraRun;
    private SystemTime currentTime;

    public WriteSMSToDocFile() {
        currentTime = new SystemTime();
        currentTime.initialize();
    }

    public String generateDocName() {
        String docname = "sms_report_" + currentTime.getFullDateTime() + ".docx";
        ModelSmsApp.docName = docname;
        return docname;
    }

    public void setDocument() {
        try {
            os = new FileOutputStream("_gendocs/" + generateDocName());
            doc = new XWPFDocument();
            para = doc.createParagraph();
            para.setAlignment(ParagraphAlignment.LEFT);
            paraRun = para.createRun();
            paraRun.setBold(false);
            paraRun.setFontSize(12);

            System.out.println("Doc name: \t" + ModelSmsApp.getDocName());

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }

    public void setDocument(String docName) {
        try {
            os = new FileOutputStream("_gendocs/" + docName);
            doc = new XWPFDocument();
            para = doc.createParagraph();
            para.setAlignment(ParagraphAlignment.LEFT);
            paraRun = para.createRun();
            paraRun.setBold(false);
            paraRun.setFontSize(12);

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }

    public void setParagraph(String sender, String date, String body) {
        paraRun.setText("From \t\t:\t" + sender);
        paraRun.addCarriageReturn();
        paraRun.setText("Date \t\t:\t" + date);
        paraRun.addCarriageReturn();
        paraRun.setText("Body \t\t:\t" + body);
        paraRun.addCarriageReturn();
        paraRun.addBreak();
    }

    public boolean doWritting() {
        try {
            doc.write(os);
            os.close();
        } catch (IOException ex) {
            Logger.getLogger(WriteSMSToDocFile.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        return true;
    }

}