org.esmerilprogramming.pdfcake.DocumentReplace.java Source code

Java tutorial

Introduction

Here is the source code for org.esmerilprogramming.pdfcake.DocumentReplace.java

Source

/*
 * PdfCake https://github.com/EsmerilProgramming
 * Copyright (C) 2014 Esmeril Programming 
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.esmerilprogramming.pdfcake;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.Enumeration;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.XmlDocumentFormatRegistry;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

/**
 * Replaces the keys and values of template to changing the real document.
 * 
 * @author eprogramming
 * 
 */
public class DocumentReplace {

    /**
     * Changes the real document file.
     * 
     * @param in
     *            InputStream
     * @param template
     *            DocumentTemplate
     * @throws Exception
     */
    public static void changeDocFile(InputStream in, DocumentTemplate template) throws Exception {
        HWPFDocument document = new HWPFDocument(in);
        document = replaceKeys(document, template);
        ByteArrayInputStream bais = getDocumentAsByteArrayIS(document);
        template.setContentBytes(convertToPdfByteArray(bais));
    }

    /**
     * Read the document searching for the $$$<keys>$$$ and replace with the values in the template
     * @param document
     * @param template
     * @return
     */
    private static HWPFDocument replaceKeys(HWPFDocument document, DocumentTemplate template) {
        Range range = document.getRange();
        for (int i = 0; i < range.numParagraphs(); i++) {
            Paragraph p = range.getParagraph(i);
            String text = null;
            for (Enumeration<String> e = template.getAttributes().keys(); e.hasMoreElements();) {
                String key = e.nextElement();
                String attributeKey = "$$$" + key + "$$$";
                try {
                    text = p.text();
                } catch (Exception ex) {
                    ;
                }
                while (text != null && text.indexOf(attributeKey) > -1) {
                    String replacement = template.getAttributes().get(key);
                    p.replaceText(attributeKey, replacement, text.indexOf(attributeKey));
                    text = text.replace(attributeKey, "");
                }
            }
        }
        return document;
    }

    /**
     * Write the document into a ByteArrayInputStream
     * @param document
     * @return
     * @throws IOException
     */
    private static ByteArrayInputStream getDocumentAsByteArrayIS(HWPFDocument document) throws IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            document.write(baos);
            try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
                return bais;
            }
        }
    }

    /**
     * Convert the document byteArrayInputStream into a pdf byteArrayOutputStream using OpenOffice library
     * @param bais
     * @return
     * @throws IOException
     */
    private static byte[] convertToPdfByteArray(ByteArrayInputStream bais) throws IOException {
        try (ByteArrayOutputStream pdfOut = new ByteArrayOutputStream()) {
            XmlDocumentFormatRegistry xdfr = loadDocumentFormats();
            DocumentFormat rtfFormat = xdfr.getFormatByFileExtension("rtf");
            DocumentFormat pdfFormat = xdfr.getFormatByFileExtension("pdf");

            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(bais, rtfFormat, pdfOut, pdfFormat);
            connection.disconnect();

            return pdfOut.toByteArray();
        }
    }

    /**
     * Read acceptable document formats
     * @return
     */
    private static XmlDocumentFormatRegistry loadDocumentFormats() {
        InputStream documentFormartIS = DocumentReplace.class.getResourceAsStream("/documentFormats.xml");
        return new XmlDocumentFormatRegistry(documentFormartIS);
    }

}