com.cib.statementstamper.windows.StatementStamperMainWindow.java Source code

Java tutorial

Introduction

Here is the source code for com.cib.statementstamper.windows.StatementStamperMainWindow.java

Source

package com.cib.statementstamper.windows;

/*
This program reads teh content ofa pdf and put some more stuff on it. 
Copyright (C) 2014 Zsolt Ladnyik
    
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/>.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.ContentByteUtils;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextMarginFinder;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.itextpdf.text.pdf.parser.Vector;
import com.vaadin.terminal.StreamResource;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FinishedEvent;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.StartedEvent;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.VerticalLayout;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class StatementStamperMainWindow extends VerticalLayout implements Receiver, Upload.FinishedListener,
        Upload.FailedListener, Upload.StartedListener, Upload.SucceededListener, RenderListener {

    private Upload upload = new Upload(null, this);
    private ByteArrayOutputStream baos = new ByteArrayOutputStream();
    private ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
    private static String bottomChunk1 = "CIB Bank Zrt. CIB Bank Ltd.";
    private static String bottomChunk2 = "H-1027 Budapest, Medve  utca 414.  H-1995 Budapest   Telefon: (06 1) 423 1000  Fax: (06 1) 489 6500 Nyilvntart cgbrsg: Fvrosi Trvnyszk Cgbrsga  Cgjegyzkszm: Cg. 01-10-041004   Adszm: 10136915-4-44  CSASZ: 17781028-5-44  Csoport kzssgi adszm: HU17781028  Tzsdetagsg: Budapesti rtktzsde Zrt. Tevkenysgi engedly szma: 957/1997/F, III/41. 044-10/2002.  BIC (SWIFT) kd: CIBHHUHB";
    private Image isplogo = null;
    private Font bottomFont;
    private Font bottomFontBold;
    private BaseFont myFontBase;
    protected Image logo = null;
    protected BaseFont baseFontArial;
    private Map<Integer, Map<Float, StringBuffer>> map = new TreeMap<Integer, Map<Float, StringBuffer>>();
    private int actualPage;

    @Override
    public void attach() {
        super.attach();
        try {
            logo = Image
                    .getInstance(StatementStamperMainWindow.class.getResource("/resources/images/cib_logo.jpg"));
            logo.setAlignment(Image.LEFT);
            logo.scalePercent(30);
            isplogo = Image
                    .getInstance(StatementStamperMainWindow.class.getResource("/resources/images/isplogo.jpg"));
            isplogo.setAlignment(Image.LEFT);
            isplogo.scalePercent(50);
            baseFontArial = BaseFont.createFont("/resources/fonts/ARIAL.TTF", BaseFont.CP1250, BaseFont.EMBEDDED);
            myFontBase = BaseFont.createFont("/resources/fonts/courbd.ttf", BaseFont.CP1250, BaseFont.EMBEDDED);
            bottomFont = new Font(baseFontArial, 7, Font.NORMAL, BaseColor.BLACK);
            bottomFontBold = new Font(baseFontArial, 7, Font.BOLD, BaseColor.BLACK);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        upload.addListener((Upload.SucceededListener) this);
        upload.addListener((Upload.StartedListener) this);
        upload.addListener((Upload.FinishedListener) this);
        upload.addListener((Upload.FailedListener) this);
        upload.setImmediate(true);
        addComponent(upload);
    }

    @Override
    public void detach() {
        super.detach();
    }

    public OutputStream receiveUpload(String filename, String mimeType) {
        return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }
        };
    }

    public void uploadSucceeded(SucceededEvent event) {

        if (!event.getMIMEType().startsWith("application/pdf")) {
            getWindow().showNotification("Error", "Ez nem pdf :" + event.getMIMEType(),
                    Notification.TYPE_ERROR_MESSAGE);
            return;
        }

        try {
            baosOut = doStamper(baos);
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }
        StreamResource.StreamSource source = new StreamResource.StreamSource() {
            public InputStream getStream() {
                return new ByteArrayInputStream(baosOut.toByteArray());
            }
        };
        //      //
        if (baosOut == null) {
            baos.reset();
            return;
        }
        String outFilename = event.getFilename();
        StreamResource resource = new StreamResource(source, outFilename, getApplication());
        resource.setMIMEType("application/pdf");
        resource.setCacheTime(0);
        getWindow().open(resource, "_blanks");
        baos.reset();
    }

    public void uploadStarted(StartedEvent event) {

    }

    public void uploadFailed(FailedEvent event) {

    }

    public void uploadFinished(FinishedEvent event) {

    }

    protected ByteArrayOutputStream doStamper(ByteArrayOutputStream baos) throws IOException, DocumentException {

        map.clear();
        ByteArrayOutputStream baosFinal = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(baos.toByteArray());

        PdfContentStreamProcessor processor = new PdfContentStreamProcessor(this);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            actualPage = i;
            PdfDictionary pageDic = reader.getPageN(i);
            PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
            processor.processContent(ContentByteUtils.getContentBytesForPage(reader, i), resourcesDic);
        }

        Document newDocument = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(newDocument, baosFinal);

        newDocument.open();
        PdfContentByte canvas = writer.getDirectContent();
        //      Font myFont = FontFactory.getFont(FontFactory.COURIER, 7, Font.BOLD);
        Iterator<Entry<Integer, Map<Float, StringBuffer>>> it = map.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<Integer, Map<Float, StringBuffer>> pairs = (Map.Entry<Integer, Map<Float, StringBuffer>>) it
                    .next();

            Iterator<Entry<Float, StringBuffer>> iter = pairs.getValue().entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<Float, StringBuffer> actualEntry = iter.next();
                canvas.beginText();
                canvas.setFontAndSize(myFontBase, 7);
                canvas.showTextAligned(Element.ALIGN_LEFT, actualEntry.getValue().toString(), 25,
                        actualEntry.getKey() + 60, 0);
                canvas.endText();
            }
            newDocument.newPage();
        }
        newDocument.close();

        reader = new PdfReader(baosFinal.toByteArray());

        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        TextMarginFinder finder;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            finder = parser.processContent(i, new TextMarginFinder());
            if (finder.getLly() <= 68) {
                getWindow().showNotification("Hiba", "A(z) " + i + ".ik oldalon tl sok a szveg !!!",
                        Notification.TYPE_ERROR_MESSAGE);
                return null;
            }
        }

        reader = new PdfReader(baosFinal.toByteArray());
        PdfStamper stamper = new PdfStamper(reader, baosFinal);
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            PdfContentByte overContent = stamper.getOverContent(i);
            overContent.addImage(logo, 131, 0, 0, 32, 44, 775);
            getFooterTable(i, n).writeSelectedRows(0, -1, 27, 68, stamper.getOverContent(i)); // ez a jo
            getIspLogoTable(i, n).writeSelectedRows(0, -1, 425, 45, stamper.getOverContent(i));
        }
        stamper.close();
        reader.close();
        return baosFinal;
    }

    protected PdfPTable getFooterTable(int x, int y) {
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(537);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(40);
        table.getDefaultCell().setBorder(Rectangle.TOP);
        table.getDefaultCell().setBorderColor(new BaseColor(221, 72, 20));
        table.getDefaultCell().setBorderWidth(1);
        table.getDefaultCell().setPaddingLeft(0);
        table.getDefaultCell().setPaddingRight(0);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        Phrase phrase = new Phrase();
        phrase.add(new Chunk(bottomChunk1, bottomFontBold));
        phrase.add(new Chunk(bottomChunk2, bottomFont));
        table.addCell(phrase);
        return table;
    }

    protected PdfPTable getIspLogoTable(int x, int y) {
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(150);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(40);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.addCell(isplogo);
        return table;
    }

    public void beginTextBlock() {
    }

    public void endTextBlock() {
    }

    public void renderImage(ImageRenderInfo renderInfo) {
    }

    public void renderText(TextRenderInfo renderInfo) {

        String text = renderInfo.getText();

        if (renderInfo.getText().equals("\u00d5")) {
            text = "\u0150";
        }
        if (renderInfo.getText().equals("\u00f5")) {
            text = "\u0151";
        }

        if (renderInfo.getText().equals("\u00db")) {
            text = "\u0170";
        }
        if (renderInfo.getText().equals("\u00ff")) {
            text = "\u0171";
        }

        if (!map.containsKey(actualPage)) {
            map.put(actualPage, new TreeMap<Float, StringBuffer>(java.util.Collections.reverseOrder()));
        }
        if (!map.get(actualPage).containsKey(renderInfo.getBaseline().getStartPoint().get(Vector.I2))) {
            map.get(actualPage).put(renderInfo.getBaseline().getStartPoint().get(Vector.I2),
                    new StringBuffer(text));
        } else {
            map.get(actualPage).get(renderInfo.getBaseline().getStartPoint().get(Vector.I2)).append(text);
        }
    }

    public void reset() {
        // TODO Auto-generated method stub

    }
}