Java tutorial
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.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.LicenseEXEntity; import com.solidmaps.webapp.entity.MapProductEntity; import com.solidmaps.webapp.enuns.TrimesterEnum; import com.solidmaps.webapp.utils.DateUtils; public class MapExercitoPdfGenerator { private static final Logger logger = Logger.getLogger(MapExercitoPdfGenerator.class); private String filePath; private CompanyEntity company; private LicenseEXEntity license; private MapProductEntity mapProduct; private List<InvoiceInventoryMapEntity> listProductMapVO; public MapExercitoPdfGenerator(String filePath, CompanyEntity company, MapProductEntity mapProduct, LicenseEXEntity license, List<InvoiceInventoryMapEntity> listProductMapVO) { this.company = company; this.listProductMapVO = listProductMapVO; this.filePath = filePath; this.mapProduct = mapProduct; this.license = license; } private Font fontHeaderTableBig = new Font(FontFamily.TIMES_ROMAN, 10f, Font.NORMAL); private Font fontHeaderTable = new Font(FontFamily.TIMES_ROMAN, 8f, Font.NORMAL); private Font fontHeaderTableSmall = new Font(FontFamily.TIMES_ROMAN, 7f, Font.NORMAL); private Font fontHeaderTableTiny = new Font(FontFamily.TIMES_ROMAN, 6.5f, Font.NORMAL); private Font fontParagraph = new Font(FontFamily.TIMES_ROMAN, 10f, Font.BOLD); private Font fontText = new Font(FontFamily.TIMES_ROMAN, 8f, 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.createFooter(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("Solid Maps"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("solidmaps"); doc.addTitle("Mapa de Produtos Controlados: " + company.getCnpjFormatted()); doc.setPageSize(PageSize.A4.rotate()); // open document doc.open(); return fileName; } private void createFooter(Document doc) throws DocumentException { Calendar cal = Calendar.getInstance(); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100f); table.setHeaderRows(0); table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); StringBuilder sbData = new StringBuilder(); sbData.append(company.getCity()).append(" / ").append(company.getState()).append(", ") .append(cal.get(Calendar.DAY_OF_MONTH)).append(" de ").append(DateUtils.getMonthName(cal)) .append(" de ").append(cal.get(Calendar.YEAR)).append("\n\n"); insertCell(table, sbData.toString(), Element.ALIGN_RIGHT, fontHeaderTableBig, false); insertCell(table, "_________________________________________________ \n Nome: " + company.getUserResponsable().getName() + " \n Cargo: " + company.getUserResponsable().getOffice(), Element.ALIGN_RIGHT, fontHeaderTable, false); doc.add(Chunk.NEWLINE); doc.add(table); } private void createParagraph(Document doc) throws DocumentException { StringBuilder sbParagraph = new StringBuilder().append("EXCELENT?SSIMO SENHOR \n").append("COMANDANTE DA ") .append(company.getRegion()).append(" REGIO MILITAR \n").append(company.getCity().toUpperCase()) .append(", ").append(company.getState()); Paragraph paragraph = new Paragraph(sbParagraph.toString()); paragraph.setFont(fontParagraph); Paragraph paragraphText = new Paragraph("A firma: " + company.getName() + ", estabelecida " + company.getState() + ", na Cidade " + company.getCity() + ", portadora do Certificado de Registro N " + license.getNumRegister() + ", vlido at " + DateUtils.format(license.getDateExpiration()) + ", apresenta V.Exa. o MAPA TRIMESTRAL DE ESTOCAGEM " + "DE PRODUTOS CONTROLADOS referente ao " + TrimesterEnum.getById(mapProduct.getNumTrimester()).getId() + " trimestre " + "de " + mapProduct.getYear() + ", de acordo com o Regulamento aprovado pelo Decreto N 3.665 de 20 de novembro de 2000, " + "para Fiscalizao de Produtos Controlados (R-105). CNPJ " + company.getCnpjFormatted()); paragraphText.setFont(fontText); doc.add(paragraph); doc.add(Chunk.NEWLINE); doc.add(paragraphText); doc.add(Chunk.NEWLINE); } private void createProductsTable(Document doc) throws DocumentException { Paragraph paragraph = new Paragraph("RESUMO GERAL"); paragraph.setFont(fontText); DecimalFormat dc = new DecimalFormat("########0.00"); // specify column widths float[] columnWidths = { 2f, 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, "GUIA DE TR?FEGO N:", Element.ALIGN_CENTER, fontHeaderTable); insertCell(table, "ENTRADA", Element.ALIGN_CENTER, fontHeaderTable); insertCell(table, "ESTOQUE DO TRIMESTRE ANTERIOR", Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, "CONSUMO", Element.ALIGN_CENTER, fontHeaderTable); insertCell(table, "ESTOQUE PARA O TRIMESTRE SEGUINTE", Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, "PROCEDNCIA (RAZO SOCIAL, ENDEREO,CIDADE, CEP, E N.DO CERTIFICADO DE REGISTRO)", Element.ALIGN_CENTER, fontHeaderTableTiny); table.setHeaderRows(1); for (InvoiceInventoryMapEntity productMap : listProductMapVO) { String companyCell = "PROCEDNCIA (" + company.getName() + ", " + company.getStreet() + ", " + company.getCity() + ", " + company.getCep() + ", " + license.getNumRegister() + ")"; // Calcula o estoque para o Trimestre seguinte 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, productMap.getTrafficGuide(), Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, dc.format(productMap.getQtdBuyProduct()), Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, dc.format(productMap.getQtdInventoryPreviusTrimester()), Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, dc.format(productMap.getQtdUtilization()), Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, dc.format(qtdNextPeriod), Element.ALIGN_CENTER, fontHeaderTableSmall); insertCell(table, companyCell, Element.ALIGN_CENTER, fontHeaderTableSmall); } doc.add(paragraph); doc.add(table); doc.add(Chunk.NEWLINE); } 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 LicenseEXEntity getLicense() { return license; } public MapProductEntity getMapProduct() { return mapProduct; } public List<InvoiceInventoryMapEntity> getListProductMapVO() { return listProductMapVO; } }