com.mstoyanov.music_lessons.pdf.CreatePDF.java Source code

Java tutorial

Introduction

Here is the source code for com.mstoyanov.music_lessons.pdf.CreatePDF.java

Source

/*   Copyright (C) 2013, Martin Stoyanov
 *   This program is free software: you can redistribute it and/or modify it under 
 *   the terms of the GNU Affero General Public License as published by the Free
 *   Software Foundation, either version 3 of the License, or (at your option) any
 *   later version.
 *
 *   This program is distributed in the hope that it will be useful, but WITHOUT 
 *   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
 *   FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more 
 *   details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.   */

package com.mstoyanov.music_lessons.pdf;

import java.io.FileOutputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.content.Context;
import android.os.Environment;
import android.widget.Toast;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.mstoyanov.music_lessons.R;
import com.mstoyanov.music_lessons.model.Cell;

public class CreatePDF {
    private static final Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
    private static final Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
    private static final Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
    private static final Font smallFont = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
    // A list of cell objects:
    private static List<Cell> cells = new ArrayList<Cell>();
    private static String[] weekdays_array;
    private static Context context;
    private static String name;

    public CreatePDF(List<Cell> cells, String name, Context context) {
        CreatePDF.cells = cells;
        CreatePDF.context = context;
        CreatePDF.name = name;
        weekdays_array = context.getResources().getStringArray(R.array.weekdays_array);
    }

    public boolean exportPDF() {
        // Checks if external storage is available:
        if (!isExternalStorageWritable()) {
            Toast.makeText(context, "External storage not accessible!", Toast.LENGTH_SHORT).show();
            return false;
        }
        // Get the path to the user's public downloads directory:
        String fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                + "/Schedule.pdf";
        try {
            Document document = new Document(PageSize.LETTER.rotate());
            PdfWriter.getInstance(document, new FileOutputStream(fileName));
            // Create a new letter sized document in landscape mode:
            document.setPageSize(PageSize.LETTER.rotate());
            document.setMargins(72, 36, 36, 36);
            document.open();
            addMetaData(document);
            addContent(document);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Toast.makeText(context, "Schedule exported to external storage/Download", Toast.LENGTH_LONG).show();
        return true;
    }

    // iTextG allows to add meta-data to the PDF, which can be viewed under File
    // -> Properties:
    private static void addMetaData(Document document) {
        document.addTitle("Music School");
        document.addSubject("Music Lessons Weekly Schedule");
        document.addKeywords("Piano, Music Theory, Lessons");
        document.addAuthor(name);
        document.addCreator("Created with iTextG under the APGL");
    }

    private static void addContent(Document document) throws DocumentException {
        String dateString = DateFormat.getDateInstance().format(new Date()).toString();
        Paragraph par = new Paragraph("Music Lessons Weekly Schedule", catFont);
        par.add(new Paragraph("Teacher: " + name + ", Created on: " + dateString, subFont));
        // Add an empty line:
        par.add(new Paragraph(" ", smallFont));
        // Add a table:
        par.add(createTable());

        document.add(par);
    }

    private static PdfPTable createTable() throws DocumentException {
        PdfPTable table = new PdfPTable(6);
        table.setTotalWidth(new float[] { 114, 114, 114, 114, 114, 114 });
        table.setLockedWidth(true);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("Monday", smallBold));
        // cell.setVerticalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Tuesday", smallBold));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Wednesday", smallBold));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Thursday", smallBold));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Friday", smallBold));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Saturday", smallBold));
        table.addCell(cell);

        table.setHeaderRows(1);

        while (cells.size() > 0) { // rows
            for (int i = 0; i < weekdays_array.length; i++) { // columns
                boolean cell_empty = true;
                // scan all cell objects:
                for (int j = 0; j < cells.size(); j++) {
                    // if there is a cell on this day:
                    if (cells.get(j).getWeekDay().equalsIgnoreCase(weekdays_array[i])) {
                        Phrase phrase = new Phrase(
                                cells.get(j).getTimeFrom() + " - " + cells.get(j).getTimeTo() + "\n"
                                        + cells.get(j).getStudentName() + "\n" + cells.get(j).getPhoneNumber(),
                                smallFont);
                        // add it to the table:
                        table.addCell(phrase);
                        cell_empty = false;
                        cells.remove(j);
                        break;
                    }
                }
                if (cell_empty) {
                    // otherwise add an empty cell:
                    table.addCell(new Phrase("\n" + "\n" + "\n", smallFont));
                }
            }
        }

        return table;
    }

    // Checks if external storage is available for read and write:
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }
}