com.solidmaps.webapp.report.MapCivilPdfGenerator.java Source code

Java tutorial

Introduction

Here is the source code for com.solidmaps.webapp.report.MapCivilPdfGenerator.java

Source

package com.solidmaps.webapp.report;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.solidmaps.webapp.entity.CompanyEntity;
import com.solidmaps.webapp.entity.InvoiceInventoryMapEntity;
import com.solidmaps.webapp.entity.InvoiceProductEntity;
import com.solidmaps.webapp.entity.LicensePCEntity;
import com.solidmaps.webapp.entity.MapProductEntity;
import com.solidmaps.webapp.utils.DateUtils;

public class MapCivilPdfGenerator {

    private static final Logger logger = Logger.getLogger(MapCivilPdfGenerator.class);

    private String filePath;

    private CompanyEntity company;

    private LicensePCEntity license;

    private MapProductEntity mapProduct;

    private List<InvoiceInventoryMapEntity> listProductMapVO;

    private List<InvoiceProductEntity> listInvoices;

    public MapCivilPdfGenerator(String filePath, CompanyEntity company, MapProductEntity mapProduct,
            LicensePCEntity license, List<InvoiceInventoryMapEntity> listProductMapVO,
            List<InvoiceProductEntity> listInvoices) {
        this.company = company;
        this.listProductMapVO = listProductMapVO;
        this.filePath = filePath;
        this.mapProduct = mapProduct;
        this.license = license;
        this.listInvoices = listInvoices;
    }

    private Font fontHeaderTable = new Font(FontFamily.TIMES_ROMAN, 8, Font.NORMAL, new BaseColor(0, 0, 0));
    private Font fontHeaderTableSmall = new Font(FontFamily.TIMES_ROMAN, 7, Font.NORMAL, new BaseColor(0, 0, 0));
    private Font fontParagraph = new Font(FontFamily.TIMES_ROMAN, 8, Font.BOLD);
    private Font fontText = new Font(FontFamily.TIMES_ROMAN, 9f, Font.BOLD);

    public String createPDF() {

        logger.info("[map ex generate begin] company: " + company.getIdCompany());

        Document doc = new Document();
        PdfWriter docWriter = null;
        String fileName = "";

        try {

            fileName = this.createDocument(doc, docWriter);
            this.createParagraph(doc);
            this.createProductsTable(doc);
            this.createSignature(doc);
            this.createInvoiceTable(doc);

        } catch (DocumentException dex) {
            dex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (doc != null) {
                // close the document
                doc.close();
            }
            if (docWriter != null) {
                // close the writer
                docWriter.close();
            }
        }

        logger.info("[map ex generate] Filename: " + fileName);

        return fileName;
    }

    private String createDocument(Document doc, PdfWriter docWriter)
            throws FileNotFoundException, DocumentException {

        String fileName = "Mapa - " + company.getCnpj() + " - " + mapProduct.getNumTrimester() + " "
                + mapProduct.getYear() + ".pdf";

        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(filePath + fileName));

        // document header attributes
        doc.addAuthor("EnforceMaps");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("EnforceMaps");
        doc.addTitle("Mapa de Produtos Controlados: " + company.getCnpjFormatted());
        doc.setPageSize(PageSize.A4.rotate());

        // open document
        doc.open();

        return fileName;
    }

    private void createSignature(Document doc) throws DocumentException {

        Calendar currDate = Calendar.getInstance();

        StringBuilder sbSignature = new StringBuilder().append(company.getCity()).append(", ")
                .append(DateUtils.getDay(currDate.getTime())).append(" de ")
                .append(DateUtils.getMonthName(currDate)).append(" de ")
                .append(DateUtils.getYear(currDate.getTime()));

        StringBuilder sbUser = new StringBuilder().append("P.P_________________________________________________ \n")
                .append("Nome: ").append(company.getUserResponsable().getName()).append("\n")
                .append("RG: " + company.getUserResponsable().getRg());

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100f);
        table.setHeaderRows(0);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

        insertCell(table, sbSignature.toString(), Element.ALIGN_LEFT, fontHeaderTable, false);
        insertCell(table, sbUser.toString(), Element.ALIGN_LEFT, fontHeaderTable, false);

        doc.add(Chunk.NEWLINE);
        doc.add(table);
    }

    private void createParagraph(Document doc) throws DocumentException {

        float[] columnWidths = { 2f, 2f };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100f);

        StringBuilder sbHeader = new StringBuilder()
                .append("SECRETARIA DE ESTADO DOS NEGCIOS DA SEGURANA PBLICA \n")
                .append("POL?CIA CIVIL DO ESTADO DE ").append(company.getState()).append("\n")
                .append("DEPARTAMENTO DE IDENTIFICAO E REGISTROS DIVERSOS \n")
                .append("DIVISO DE PRODUTOS CONTROLADOS \n");

        StringBuilder sbHeaderMonth = new StringBuilder().append("MAPA TRIMESTRAL DEMONSTRATIVO DO ESTOQUE \n")
                .append("DE COMPRAS, VENDAS E CONSUMO \n").append("REFERENTE AO ")
                .append(mapProduct.getNumTrimester()).append(" TRIMESTRE DO ANO DE ").append(mapProduct.getYear())
                .append(".");

        StringBuilder sbCompany = new StringBuilder().append("Empresa: ").append(company.getName().toUpperCase())
                .append(" estabelecida  ").append(company.getStreet().toUpperCase()).append(" Cidade: ")
                .append(company.getCity()).append(", Estado: ").append(company.getState()).append(", CEP: ")
                .append(company.getCep()).append(", Fone: (").append(company.getUserResponsable().getPhoneDDD())
                .append(") ").append(company.getUserResponsable().getPhoneNumber()).append(", Fax: (")
                .append(company.getUserResponsable().getPhoneDDD()).append(") ")
                .append(company.getUserResponsable().getNumFax());

        // insert column headings
        insertCell(table, sbHeader.toString(), Element.ALIGN_LEFT, fontParagraph);
        insertCell(table, sbHeaderMonth.toString(), Element.ALIGN_LEFT, fontText);

        Paragraph paragraphText = new Paragraph(sbCompany.toString());
        paragraphText.setFont(fontHeaderTable);

        doc.add(Chunk.NEWLINE);
        doc.add(table);
        doc.add(Chunk.NEWLINE);
        doc.add(paragraphText);
        doc.add(Chunk.NEWLINE);
    }

    private void createProductsTable(Document doc) throws DocumentException {

        DecimalFormat dc = new DecimalFormat("########0.00");

        // specify column widths
        float[] columnWidths = { 2f, 2f, 2f, 2f, 2f, 2.5f };
        // create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(100f);

        // insert column headings
        insertCell(table, "PRODUTO", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "SALDO DO TRIMESTRE ANTERIOR", Element.ALIGN_CENTER, fontHeaderTableSmall);
        insertCell(table, "COMPRAS", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "VENDAS", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "CONSUMO", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "ESTOQUE PARA O TRIMESTRE SEGUINTE", Element.ALIGN_CENTER, fontHeaderTableSmall);

        table.setHeaderRows(1);

        for (InvoiceInventoryMapEntity productMap : listProductMapVO) {

            BigDecimal qtdNextPeriod = productMap.getQtdInventoryPreviusTrimester()
                    .add(productMap.getQtdBuyProduct()).subtract(productMap.getQtdSellProduct())
                    .subtract(productMap.getQtdUtilization());

            // Cria a tabela com os Produtos
            insertCell(table, productMap.getProduct().getName(), Element.ALIGN_CENTER, fontHeaderTableSmall);
            insertCell(table, dc.format(productMap.getQtdInventoryPreviusTrimester()), Element.ALIGN_CENTER,
                    fontHeaderTableSmall);
            insertCell(table, dc.format(productMap.getQtdBuyProduct()), Element.ALIGN_CENTER, fontHeaderTableSmall);
            insertCell(table, dc.format(productMap.getQtdSellProduct()), Element.ALIGN_CENTER,
                    fontHeaderTableSmall);
            insertCell(table, dc.format(productMap.getQtdUtilization()), Element.ALIGN_CENTER,
                    fontHeaderTableSmall);
            insertCell(table, dc.format(qtdNextPeriod), Element.ALIGN_CENTER, fontHeaderTableSmall);
        }

        doc.add(table);
    }

    private void createInvoiceTable(Document doc) throws DocumentException {

        doc.add(Chunk.NEWLINE);

        // Ajusta o cabealho
        float[] columnHeader = { 1f };
        PdfPTable tableHeader = new PdfPTable(columnHeader);
        tableHeader.setWidthPercentage(100f);
        insertCell(tableHeader, "\n RELAO DE COMPRAS DURANTE  O TRIMESTRE \n", Element.ALIGN_CENTER, fontText);

        doc.add(tableHeader);

        doc.add(Chunk.NEWLINE);

        // specify column widths
        float[] columnWidths = { 2f, 2f, 2f, 2f, 2f, 2f, 2.5f, 2f };
        // create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(100f);

        // insert column headings
        insertCell(table, "Data:", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "Empresa Vendedora", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "Endereo", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "Cidade/UF", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "CEP", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "N. nota Fiscal", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "Produto", Element.ALIGN_CENTER, fontHeaderTable);
        insertCell(table, "Quantidade", Element.ALIGN_CENTER, fontHeaderTable);

        table.setHeaderRows(1);

        for (InvoiceProductEntity invoiceProduct : this.listInvoices) {
            insertCell(table, DateUtils.format(invoiceProduct.getInvoice().getDateCreate()), Element.ALIGN_CENTER,
                    fontHeaderTable);
            insertCell(table, invoiceProduct.getInvoice().getProvider().getCnpj(), Element.ALIGN_CENTER,
                    fontHeaderTable);
            insertCell(table, invoiceProduct.getInvoice().getProvider().getStreet(), Element.ALIGN_CENTER,
                    fontHeaderTable);
            insertCell(table, invoiceProduct.getInvoice().getProvider().getCity(), Element.ALIGN_CENTER,
                    fontHeaderTable);
            insertCell(table, invoiceProduct.getInvoice().getProvider().getCep(), Element.ALIGN_CENTER,
                    fontHeaderTable);
            insertCell(table, invoiceProduct.getInvoice().getNumInvoice(), Element.ALIGN_CENTER, fontHeaderTable);
            insertCell(table, invoiceProduct.getProduct().getProductOfficial().getName(), Element.ALIGN_CENTER,
                    fontHeaderTable);
            insertCell(table, invoiceProduct.getQtdProduct() + invoiceProduct.getTypeQtdProduct(),
                    Element.ALIGN_CENTER, fontHeaderTable);
        }

        doc.add(table);
    }

    private void insertCell(PdfPTable table, String text, int align, Font font) {

        this.insertCell(table, text, align, font, true);

    }

    private void insertCell(PdfPTable table, String text, int align, Font font, boolean border) {

        if (text == null) {
            text = "";
        }

        // create a new cell with the specified Text and Font
        PdfPCell cell = new PdfPCell(new Phrase(text.trim(), font));
        // set the cell alignment
        cell.setHorizontalAlignment(align);
        // in case there is no text and you wan to create an empty row
        if (text.trim().equalsIgnoreCase("")) {
            cell.setMinimumHeight(10f);
        }

        if (!border) {
            cell.setBorder(Rectangle.NO_BORDER);
        }

        // add the call to the table
        table.addCell(cell);
    }

    public CompanyEntity getCompany() {
        return company;
    }

    public LicensePCEntity getLicense() {
        return license;
    }

    public MapProductEntity getMapProduct() {
        return mapProduct;
    }

    public List<InvoiceInventoryMapEntity> getListProductMapVO() {
        return listProductMapVO;
    }

}