name.marcelomorales.siqisiqi.pdfbox.CoordinatesGenerator.java Source code

Java tutorial

Introduction

Here is the source code for name.marcelomorales.siqisiqi.pdfbox.CoordinatesGenerator.java

Source

/*
 * Copyright 2013 Marcelo Morales me@marcelomorales.name
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package name.marcelomorales.siqisiqi.pdfbox;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.io.CharStreams;
import com.google.common.io.Closeables;
import com.typesafe.config.Config;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import static java.lang.Float.parseFloat;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA_BOLD;

/**
 * @author Marcelo Morales
 *         Since: 8/26/13
 */
public class CoordinatesGenerator {

    private static final Logger LOGGER = LoggerFactory.getLogger(CoordinatesGenerator.class);

    private final Config config;

    @Inject
    public CoordinatesGenerator(Config config) {
        this.config = config;
    }

    public void generarPdf(OutputStream os, String template, Map<String, Object> m, String path, String coordenates,
            float fontSize, float ancho) throws IOException {
        long t = System.currentTimeMillis();
        PDDocument doc = null;
        try {
            doc = PDDocument.load(new File(path));

            List pages = doc.getDocumentCatalog().getAllPages();

            PDPage sourcePage = (PDPage) pages.get(0);

            boolean append = sourcePage.getContents() != null;
            PDPageContentStream contentStream = new PDPageContentStream(doc, sourcePage, append, true);

            StringReader fileReader = null;
            try {

                fileReader = new StringReader(template);
                List<String> list = CharStreams.readLines(fileReader);
                boolean textHasBegun = false;
                float currentOffset = 0f;
                for (String line : list) {

                    if (line == null) {
                        continue;
                    }

                    if (line.startsWith("#")) {
                        continue;
                    }

                    final Iterable<String> str = Splitter.on(',').omitEmptyStrings().trimResults().split(line);
                    final String[] split = Iterables.toArray(str, String.class);
                    if (split == null || split.length < 4) {
                        continue;
                    }

                    if (Character.isDigit(split[0].charAt(0))) {
                        if (textHasBegun) {
                            contentStream.endText();
                        }
                        contentStream.beginText();
                        textHasBegun = true;
                        contentStream.moveTextPositionByAmount(parseFloat(split[0]), parseFloat(split[1]));
                    } else {
                        contentStream.moveTextPositionByAmount(currentOffset, 0);
                    }

                    if (!textHasBegun) {
                        LOGGER.warn("Hay un posible mal uso de un .ree", new Throwable());
                        contentStream.beginText();
                        textHasBegun = true;
                    }

                    PDType1Font font;
                    if ("b".equals(split[2])) {
                        font = HELVETICA_BOLD;
                    } else {
                        font = HELVETICA;
                    }
                    contentStream.setFont(font, fontSize);

                    Object text = null;
                    if (split[3].startsWith("\"")) {
                        // TODO: text = substring(split[3], 1, -1);
                    } else {
                        // TODO: text = new PropertyModel(m, split[3]).getObject();
                    }

                    if (text == null) {
                        LOGGER.warn("Propiedad {} no se encuentra", split[3]);
                        //contentStream.drawString("ERROR: propiedad no encontrada");
                        contentStream.drawString(" ");
                    } else {
                        String string = text.toString();
                        currentOffset = font.getStringWidth(string) * ancho;
                        contentStream.drawString(string);
                    }
                }

                if (textHasBegun) {
                    contentStream.endText();
                }
            } finally {
                Closeables.closeQuietly(fileReader);
            }

            contentStream.close();

            try {
                doc.save(os);
            } catch (COSVisitorException e) {
                throw new IOException("Ha ocurrido un error al escribir en el Os", e);
            }
        } finally {
            if (doc != null) {
                doc.close();
            }
            LOGGER.info("Me ha tomado {} milisegundos hacer el pdf", System.currentTimeMillis() - t);
        }
    }

}