Search in sources :

Example 1 with FormPrintException

use of org.jaffa.modules.printing.services.exceptions.FormPrintException in project jaffa-framework by jaffa-projects.

the class PdfHelper method removeRotation.

/**
 * Remove the rotation from the pdfOutput document pages.
 */
private static byte[] removeRotation(byte[] pdfOutput) throws FormPrintException {
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(pdfOutput);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException("Remove PDF Page Rotation  - Failed to create a PDF Reader");
        log.error(" Remove PDF Page Rotation  - Failed to create a PDF Reader ");
        throw e;
    }
    boolean needed = false;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        if (currentReader.getPageRotation(i) != 0) {
            needed = true;
        }
    }
    if (!needed) {
        return pdfOutput;
    }
    OutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException("Remove PDF Page Rotation  - Failed to create a PDF Writer");
        log.error(" Remove PDF Page Rotation  - Failed to create a PDF Writer ");
        throw e;
    }
    PdfContentByte cb = null;
    PdfImportedPage page;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        // strip rotation
        currentSize = new Rectangle(currentSize.getWidth(), currentSize.getHeight());
        document.setPageSize(currentSize);
        if (cb == null) {
            document.open();
            cb = writer.getDirectContent();
        } else {
            document.newPage();
        }
        int rotation = currentReader.getPageRotation(i);
        page = writer.getImportedPage(currentReader, i);
        float a, b, c, d, e, f;
        if (rotation == 0) {
            a = 1;
            b = 0;
            c = 0;
            d = 1;
            e = 0;
            f = 0;
        } else if (rotation == 90) {
            a = 0;
            b = -1;
            c = 1;
            d = 0;
            e = 0;
            f = currentSize.getHeight();
        } else if (rotation == 180) {
            a = -1;
            b = 0;
            c = 0;
            d = -1;
            e = currentSize.getWidth();
            f = currentSize.getHeight();
        } else if (rotation == 270) {
            a = 0;
            b = 1;
            c = -1;
            d = 0;
            e = currentSize.getWidth();
            f = 0;
        } else {
            FormPrintException ex = new PdfProcessingException("Remove PDF Page Rotation - Unparsable rotation value: " + rotation);
            log.error(" Remove PDF Page Rotation - Unparsable form rotation value: " + rotation);
            throw ex;
        }
        cb.addTemplate(page, a, b, c, d, e, f);
    }
    document.close();
    return ((ByteArrayOutputStream) baos).toByteArray();
}
Also used : PdfProcessingException(org.jaffa.modules.printing.services.exceptions.PdfProcessingException) PdfWriter(com.lowagie.text.pdf.PdfWriter) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Rectangle(com.lowagie.text.Rectangle) PdfReader(com.lowagie.text.pdf.PdfReader) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) PdfImportedPage(com.lowagie.text.pdf.PdfImportedPage) DocumentException(com.lowagie.text.DocumentException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Example 2 with FormPrintException

use of org.jaffa.modules.printing.services.exceptions.FormPrintException in project jaffa-framework by jaffa-projects.

the class FormData method renderTemplate.

public String[] renderTemplate() throws ApplicationExceptions {
    if (m_velocityTemplate != null && m_velocityTemplate.length() > 0 && !m_velocityTemplate.startsWith("???")) {
        try {
            VelocityTemplateHelper vth = new VelocityTemplateHelper();
            vth.setDataSource(this);
            vth.setTemplate(m_velocityTemplate);
            return (vth.renderTemplateLines());
        } catch (FormPrintException fpe) {
            fpe.printStackTrace();
            throw new ApplicationExceptions(new ApplicationException("exception.org.jaffa.modules.printing.services.FormData.VelocityTemplateError") {
            });
        }
    } else {
        return (null);
    }
}
Also used : ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) ApplicationException(org.jaffa.exceptions.ApplicationException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException)

Example 3 with FormPrintException

use of org.jaffa.modules.printing.services.exceptions.FormPrintException in project jaffa-framework by jaffa-projects.

the class FormPrintEngineIText method fillPageFields.

/**
 * This will fill in the page with data,
 * m_currentPageData contains the details of the current page being printed
 * @throws FormPrintException Thrown if there is any form processing problems
 */
protected void fillPageFields() throws FormPrintException {
    log.debug("fillPageFields: Page=" + getCurrentPage());
    try {
        PdfContentByte cb = m_writer.getDirectContent();
        PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData();
        // Loop through each field to be inserted
        for (Iterator i = page.fieldList.iterator(); i.hasNext(); ) {
            String fieldname = (String) i.next();
            // Get the properties for displaying this field
            FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname);
            // Get the data to display
            FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData);
            // Caluclate Clipping Region
            float x1 = Math.min(props.x1, props.x2);
            float x2 = Math.max(props.x1, props.x2);
            float y1 = Math.min(props.y1, props.y2);
            float y2 = Math.max(props.y1, props.y2);
            float w = Math.abs(props.x1 - props.x2) + 1;
            float h = Math.abs(props.y1 - props.y2) + 1;
            if (log.isDebugEnabled())
                log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->(" + x2 + "," + y2 + ")]");
            // Default the font if not specified
            String font = BaseFont.HELVETICA;
            if (props.fontFace != null)
                font = props.fontFace;
            // Handle Barcodes diffently withing iText, don't just use fonts
            if (font.startsWith("Barcode")) {
                String bcClassName = "com.lowagie.text.pdf." + font;
                Object bcode = null;
                String dataStr = data.getValue();
                if (dataStr != null) {
                    log.debug("Barcode Data String = " + dataStr);
                    // Try and create the correct Barcode Object
                    try {
                        Class bcClass = Class.forName(bcClassName);
                        bcode = bcClass.newInstance();
                    } catch (Exception e) {
                        String err = "Can't Create Barcode Object for barcode type '" + font + "' on field " + fieldname;
                        log.error(err, e);
                    }
                    // Only continue if the barcode object was created
                    if (bcode != null) {
                        // Generate and Print barcode, based on common interface
                        if (bcode instanceof Barcode) {
                            Barcode b = (Barcode) bcode;
                            // Set some default output a barcode
                            b.setCode(dataStr);
                            if (props.fontSize <= 0) {
                                // Hide text if font size is 0, and make the barcode height the size of the box
                                b.setBarHeight(h);
                                b.setFont(null);
                            } else {
                                // size of text under barcode
                                b.setSize(props.fontSize);
                                // Adjust Bar Height to allow for font size
                                b.setBarHeight(h - props.fontSize - 5);
                            }
                            // Wide Bars
                            b.setN(2);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            // Print out barcode
                            Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null);
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        } else // Print PDF417 barcode, not based on common interface
                        if (bcode instanceof BarcodePDF417) {
                            BarcodePDF417 b = (BarcodePDF417) bcode;
                            // Set some default output a barcode
                            b.setText(dataStr);
                            b.setErrorLevel(5);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n" + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows() + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight=" + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n" + "Options=" + b.getOptions() + "\n" + "LenCodewords=" + b.getLenCodewords());
                            // Print out barcode
                            // image = b.getImage();
                            printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        } else {
                            // Error, unknown barcode
                            String err = "Error, No print handler for barcode object " + bcode.getClass().getName();
                            log.error(err);
                        // throw new EngineProcessingException(err);
                        }
                    }
                } else
                    log.debug("SKIPPED BARCODE : No data for " + fieldname);
            // Handle Images differently within iText, native support for JFreeChart
            } else if ("image".equalsIgnoreCase(font)) {
                try {
                    java.awt.Image image = data.getDomImage();
                    // Add an image to the page
                    if (image != null) {
                        if (fieldname.startsWith("watermark")) {
                            // Add an image-based watermark to the under content layer
                            PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                            if (props.opacity != 1f) {
                                PdfGState gs = new PdfGState();
                                gs.setFillOpacity(props.opacity);
                                contentUnder.setGState(gs);
                            }
                            printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        } else {
                            // Add an image to main page layer
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        }
                    }
                } catch (IOException e) {
                    // Add Error on page.
                    Phrase text = new Phrase("Image Error", FontFactory.getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red")));
                    ColumnText ct = new ColumnText(cb);
                    ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT);
                }
            } else if (fieldname.startsWith("watermark")) {
                // Add a text-based watermark
                String text = data.getValue();
                PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                if (props.opacity != 1f) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(props.opacity);
                    contentUnder.setGState(gs);
                }
                // The text aligns (left, center, right) on the pivot point.
                // Default to align left.
                float pivotX = x1;
                float pivotY = y1;
                if (Element.ALIGN_CENTER == props.align) {
                    pivotX = (x1 / 2) + (x2 / 2);
                    pivotY = y1;
                } else if (Element.ALIGN_RIGHT == props.align) {
                    pivotX = x2;
                    pivotY = y1;
                }
                Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor)));
                ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate);
            } else {
                // Handle printing of basic Text
                float lineHeight = props.fontSize;
                String str = data.getValue();
                if (str != null) {
                    // Add a bounded column to add text to.
                    Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(props.color)));
                    ColumnText ct = new ColumnText(cb);
                    if (props.fitMethod == FIT_METHOD_CLIP)
                        // set up column with height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align);
                    else
                        // set up column without (i.e. large) height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align);
                    ct.go();
                }
            }
            // Draw outline boxes arround fields
            if (isTemplateMode()) {
                cb.setLineWidth(0.5f);
                cb.setLineDash(4f, 2f);
                cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0));
                cb.moveTo(x1, y1);
                cb.lineTo(x1, y2);
                cb.lineTo(x2, y2);
                cb.lineTo(x2, y1);
                cb.lineTo(x1, y1);
                cb.stroke();
            }
        }
    // end for-loop
    } catch (DocumentException e) {
        String err = "Error printing data - " + e.getMessage();
        log.error(err, e);
        throw new EngineProcessingException(err);
    // } catch (IOException e) {
    // String err = "Error printing data - " + e.getMessage();
    // log.error(err ,e);
    // throw new EngineProcessingException(err);
    }
}
Also used : BarcodePDF417(com.lowagie.text.pdf.BarcodePDF417) Color(java.awt.Color) IOException(java.io.IOException) Phrase(com.lowagie.text.Phrase) Image(com.lowagie.text.Image) BadElementException(com.lowagie.text.BadElementException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) FileNotFoundException(java.io.FileNotFoundException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) ColumnText(com.lowagie.text.pdf.ColumnText) Barcode(com.lowagie.text.pdf.Barcode) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator) PdfContentByte(com.lowagie.text.pdf.PdfContentByte) PdfGState(com.lowagie.text.pdf.PdfGState)

Example 4 with FormPrintException

use of org.jaffa.modules.printing.services.exceptions.FormPrintException in project jaffa-framework by jaffa-projects.

the class FormPrintEngineVelocity method generate.

public void generate() throws FormPrintException {
    // make a Context and put data into it
    log.debug("Set Up Context");
    VelocityContext context = new VelocityContext();
    context.put("data", getDataSource());
    fmt = new FormFormatHelper();
    context.put("fmt", fmt);
    context.put("context", ContextManagerFactory.instance().getThreadContext());
    log.debug("data=" + BeanMoulder.printBean(getDataSource()));
    // Split the template file between path and name
    File templateFile = new File(getTemplateName());
    if (!templateFile.exists()) {
        String err = "Velocity Template Not Found - " + getTemplateName();
        log.error(err);
        throw new EngineProcessingException(err);
    }
    String path = templateFile.getParent();
    // (templateFile.getParent()==null?getTemplateName():getTemplateName().substring(templateFile.getParent().length()));
    String file = templateFile.getName();
    if (path != null) {
        Velocity.setProperty("file.resource.loader.path", path);
    }
    log.debug("SearchPath = " + path + ", template = " + file);
    // init the runtime engine.  Defaults are fine.
    try {
        Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
        Velocity.init();
        log.debug("Initialized Velocity");
    } catch (Exception e) {
        String err = "Velocity Initialization - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    }
    // Try and load the template
    Template template = null;
    try {
        log.debug("Velocity file.resource.loader.path property = " + Velocity.getProperty("file.resource.loader.path"));
        template = Velocity.getTemplate(file);
    } catch (ResourceNotFoundException e) {
        String err = "Error opening template - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    } catch (ParseErrorException e) {
        String err = "Template Parse Error - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    } catch (Exception e) {
        String err = "Template Load Error - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    }
    try {
        m_output = new StringWriter();
        // render a template
        template.merge(context, m_output);
        // log.debug("Generated outbut based on template...\n" + m_output.getBuffer().toString());
        m_processed = true;
    } catch (Exception e) {
        String err = "Velocity Error - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    }
}
Also used : StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) ParseErrorException(org.apache.velocity.exception.ParseErrorException) SplitString(org.jaffa.util.SplitString) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) File(java.io.File) ParseErrorException(org.apache.velocity.exception.ParseErrorException) IOException(java.io.IOException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) Template(org.apache.velocity.Template)

Example 5 with FormPrintException

use of org.jaffa.modules.printing.services.exceptions.FormPrintException in project jaffa-framework by jaffa-projects.

the class MultiFormPrintEngine method generate.

/**
 * The core method in the engine is the generate() method, it must only be
 * called once, and must be called before you call any method that
 * accessed the generated PDF ( like writeForm() or getGeneratedForm() )
 *
 * @throws FormPrintException This is thrown if there is any error in generating the PDF document.
 * The details will be in the message text
 */
public void generate() throws FormPrintException {
    if (m_processed)
        throw new IllegalStateException("The form has already been processed");
    int pageOffset = 0;
    // Create a factory for each object, and initialize
    int index = -1;
    for (String templateName : m_templateFilenames) {
        index++;
        // Create a print engine
        IFormPrintEngine engine = FormPrintFactory.newInstance(m_engineType);
        if (engine == null) {
            String err = "No Engine Created. Type=" + m_engineType;
            if (log.isDebugEnabled())
                log.error(err);
            throw new EngineInstantiationException(err);
        }
        m_engines.add(engine);
        // Set all values on print engine
        engine.setTemplateName(templateName);
        engine.setDataSource(m_objectModels.get(index));
        engine.setPermissions(m_canPrint, m_canCopy, m_canModify);
        if (m_documentProperties != null)
            engine.setDocumentProperties(m_documentProperties);
        if (m_searchPath != null)
            engine.setTemplateSearchPath(m_searchPath);
        engine.initialize();
        m_totalPages += engine.getTotalPages();
    }
    // IFormPrintEngine engine = it.next();
    for (IFormPrintEngine engine : m_engines) {
        // Set all values on print engine
        engine.setTotalPagesOverride(m_totalPages);
        engine.setCurrentPageOffset(pageOffset);
        engine.generate();
        m_documents.add(engine.getGeneratedForm());
        pageOffset += engine.getTotalPages();
    }
    // Now merge the outputs
    try {
        if (FormPrintFactory.ENGINE_TYPE_ITEXT.equals(m_engineType) || FormPrintFactory.ENGINE_TYPE_FOP.equals(m_engineType) || FormPrintFactory.ENGINE_TYPE_PDFLIB.equals(m_engineType)) {
            m_output = mergePdf(m_documents);
            if (getPageSize() != null) {
                m_output = PdfHelper.scalePdfPages(m_output, getPageSize(), false, true);
            }
        } else {
            m_output = mergeText(m_documents);
        }
    } catch (FormPrintException fpe) {
        throw fpe;
    } catch (Exception e) {
        log.error("Failed to merge PDF documents", e);
        throw new EngineProcessingException("Merge Failed", e);
    }
    m_processed = true;
}
Also used : EngineInstantiationException(org.jaffa.modules.printing.services.exceptions.EngineInstantiationException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) EngineInstantiationException(org.jaffa.modules.printing.services.exceptions.EngineInstantiationException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) PdfProcessingException(org.jaffa.modules.printing.services.exceptions.PdfProcessingException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException)

Aggregations

FormPrintException (org.jaffa.modules.printing.services.exceptions.FormPrintException)8 IOException (java.io.IOException)6 EngineProcessingException (org.jaffa.modules.printing.services.exceptions.EngineProcessingException)5 DocumentException (com.lowagie.text.DocumentException)4 PdfContentByte (com.lowagie.text.pdf.PdfContentByte)3 PdfProcessingException (org.jaffa.modules.printing.services.exceptions.PdfProcessingException)3 Document (com.lowagie.text.Document)2 Rectangle (com.lowagie.text.Rectangle)2 PdfImportedPage (com.lowagie.text.pdf.PdfImportedPage)2 PdfReader (com.lowagie.text.pdf.PdfReader)2 PdfWriter (com.lowagie.text.pdf.PdfWriter)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 OutputStream (java.io.OutputStream)2 StringWriter (java.io.StringWriter)2 VelocityContext (org.apache.velocity.VelocityContext)2 MethodInvocationException (org.apache.velocity.exception.MethodInvocationException)2 ParseErrorException (org.apache.velocity.exception.ParseErrorException)2 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)2