PageRenderTime 940ms CodeModel.GetById 172ms app.highlight 503ms RepoModel.GetById 156ms app.codeStats 1ms

/src/mpv5/utils/export/PDFFile.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 166 lines | 133 code | 13 blank | 20 comment | 19 complexity | 07ea6c3422c1a44a173518512da1a36a MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.utils.export;
 18
 19import com.lowagie.text.BadElementException;
 20import com.lowagie.text.DocumentException;
 21import com.lowagie.text.Image;
 22import com.lowagie.text.Rectangle;
 23import com.lowagie.text.pdf.AcroFields;
 24import com.lowagie.text.pdf.PdfContentByte;
 25import com.lowagie.text.pdf.PdfReader;
 26import com.lowagie.text.pdf.PdfStamper;
 27import enoa.handler.TableHandler;
 28import java.awt.Color;
 29import java.io.FileOutputStream;
 30import java.io.IOException;
 31import java.util.HashMap;
 32import java.util.Iterator;
 33import java.util.List;
 34import mpv5.db.objects.Template;
 35import mpv5.logging.Log;
 36import mpv5.utils.images.MPIcon;
 37
 38/**
 39 *
 40 *  
 41 */
 42public class PDFFile extends Exportable {
 43
 44    private PdfReader template;
 45    private AcroFields acroFields;
 46
 47    public PDFFile(String pathToFile) {
 48        super(pathToFile);
 49    }
 50
 51    @Override
 52    public void run() {
 53
 54
 55        Log.Debug(this, "All fields:");
 56        for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) {
 57            String k = it.next();
 58            Log.Debug(this, "Key: " + k + " [" + getData().get(k) + "]");
 59        }
 60        try {
 61            Log.Debug(this, "Running export for template file: " + getPath() + "  to file: " + getTarget());
 62            try {
 63                template = new PdfReader(getPath());
 64            } catch (Exception iOException) {
 65                Log.Debug(iOException);
 66            }
 67            Log.Debug(this, "Checking PDF File: " + getPath());
 68            acroFields = template.getAcroFields();
 69            Log.Debug(this, "Creating PDF File: " + getTarget().getPath());
 70            PdfStamper pdfStamper = new PdfStamper(template, new FileOutputStream(getTarget().getPath()));
 71            pdfStamper.setFormFlattening(true);
 72            acroFields = pdfStamper.getAcroFields();
 73            HashMap PDFFields = acroFields.getFields();
 74            for (Iterator it = PDFFields.keySet().iterator(); it.hasNext();) {
 75                Object object = it.next();
 76                String keyt = String.valueOf(object);
 77                if (getData().get(keyt) != null) {
 78                    Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]");
 79                    if (!keyt.startsWith("image")) {
 80                        acroFields.setField(keyt, String.valueOf(getData().get(keyt)));
 81                    } else {
 82                        setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage());
 83                    }
 84                }
 85                if (getData().get(keyt.replace("_", ".")) != null) {
 86                    Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]");
 87                    if (!keyt.startsWith("image")) {
 88                        acroFields.setField(keyt, String.valueOf(getData().get(keyt.replace("_", "."))));
 89                    } else {
 90                        setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage());
 91                    }
 92                }
 93            }
 94
 95            Log.Debug(this, "Looking for tables in: " + getName());
 96            for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) {
 97                String key = it.next();
 98                if (key.contains(TableHandler.KEY_TABLE)) {//Table found
 99                    @SuppressWarnings("unchecked")
100                    List<String[]> value = (List<String[]>) getData().get(key);
101                    for (int i = 0; i < value.size(); i++) {
102                        String[] strings = value.get(i);
103                        if (getTemplate() != null) {
104                            strings = refactorRow(getTemplate(), strings);
105                        }
106                        for (int j = 0; j < strings.length; j++) {
107                            String cellValue = strings[j];
108                            String fieldname = "col" + j + "row" + i;
109                            Log.Debug(this, "Filling Field: " + fieldname + " [" + getData().get(cellValue) + "]");
110                            acroFields.setField(fieldname, cellValue);
111                        }
112                    }
113                }
114            }
115
116            pdfStamper.close();
117            Log.Debug(this, "Done file: " + getTarget().getPath());
118        } catch (Exception ex) {
119            Log.Debug(ex);
120        }
121    }
122
123    private void setImage(PdfStamper stamper, String key, java.awt.Image oimg) {
124        try {
125            Log.Debug(this, "Write Image.." + key);
126            float[] photograph = acroFields.getFieldPositions(key);
127            Rectangle rect = new Rectangle(photograph[1], photograph[2], photograph[3], photograph[4]);
128            Image img = Image.getInstance(oimg, null);
129
130            img.setAbsolutePosition(photograph[1] + (rect.getWidth() - img.getScaledWidth()) / 2, photograph[2] + (rect.getHeight() - img.getScaledHeight()) / 2);
131            PdfContentByte cb = stamper.getOverContent((int) photograph[0]);
132            cb.addImage(img);
133        } catch (Exception iOException) {
134            Log.Debug(iOException);
135        }
136    }
137
138    private String[] refactorRow(Template template, String[] possibleCols) {
139        String format = template.__getFormat();
140        int[] intcols;
141        try {
142            String[] cols = format.split(",");
143            intcols = new int[cols.length];
144            for (int i = 0; i < intcols.length; i++) {
145                String string = cols[i];
146                intcols[i] = Integer.valueOf(string).intValue();
147            }
148        } catch (Exception ex) {
149            Log.Debug(this, "An error occured, using default format now. " + ex.getMessage());
150            intcols = new int[possibleCols.length];
151            for (int i = 0; i < intcols.length; i++) {
152                intcols[i] = i + 1;
153            }
154        }
155        String[] form = new String[intcols.length];
156        for (int i = 0; i < intcols.length; i++) {
157            try {
158                form[i] = possibleCols[intcols[i] - 1];
159            } catch (Exception e) {
160                Log.Debug(this, "To much columns in the format definition: " + e);
161            }
162        }
163
164        return form;
165    }
166}