Search in sources :

Example 6 with FormPrintException

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

the class PdfHelper method scalePdfPages.

/**
 * Scale the pages of the input pdfOutput document to the given pageSize.
 * @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream.
 * @param pageSize The new page size to which to scale to PDF document, e.g. "A4".
 * @param noEnlarge If true, center pages instead of enlarging them.
 *        Use noEnlarge if the new page size is larger than the old one
 *        and the pages should be centered instead of enlarged.
 * @param preserveAspectRatio If true, the aspect ratio will be preserved.
 * @return The PDF document with its pages scaled to the input pageSize.
 */
public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge, boolean preserveAspectRatio) throws FormPrintException {
    if (pageSize == null || pdfOutput == null) {
        return pdfOutput;
    }
    // Get the dimensions of the given pageSize in PostScript points.
    // A PostScript point is a 72th of an inch.
    float dimX;
    float dimY;
    Rectangle rectangle;
    try {
        rectangle = PageSize.getRectangle(pageSize);
    } catch (Exception ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Invalid page size = " + pageSize + "  ");
        log.error(" scalePdfPages  - Invalid page size: " + pageSize + ".  " + ex.getMessage() + ". ");
        throw e;
    }
    if (rectangle != null) {
        dimX = rectangle.getWidth();
        dimY = rectangle.getHeight();
    } else {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Invalid page size: " + pageSize);
        log.error(" scalePdfPages  - Invalid page size: " + pageSize);
        throw e;
    }
    // Create portrait and landscape rectangles for the given page size.
    Rectangle portraitPageSize;
    Rectangle landscapePageSize;
    if (dimY > dimX) {
        portraitPageSize = new Rectangle(dimX, dimY);
        landscapePageSize = new Rectangle(dimY, dimX);
    } else {
        portraitPageSize = new Rectangle(dimY, dimX);
        landscapePageSize = new Rectangle(dimX, dimY);
    }
    // Remove the document rotation before resizing the document.
    byte[] output = removeRotation(pdfOutput);
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(output);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Reader");
        log.error(" scalePdfPages  - Failed to create a PDF Reader ");
        throw e;
    }
    OutputStream baos = new ByteArrayOutputStream();
    Rectangle newSize = new Rectangle(dimX, dimY);
    Document document = new Document(newSize, 0, 0, 0, 0);
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Writer");
        log.error(" scalePdfPages  - Failed to create a PDF Writer ");
        throw e;
    }
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfImportedPage page;
    float offsetX, offsetY;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        if (currentReader.getPageRotation(i) != 0) {
            FormPrintException e = new PdfProcessingException("Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form.");
            log.error(" Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form. ");
            throw e;
        }
        // Reset the page size for each page because there may be a mix of sizes in the document.
        float currentWidth = currentSize.getWidth();
        float currentHeight = currentSize.getHeight();
        if (currentWidth > currentHeight) {
            newSize = landscapePageSize;
        } else {
            newSize = portraitPageSize;
        }
        document.setPageSize(newSize);
        document.newPage();
        float factorX = newSize.getWidth() / currentSize.getWidth();
        float factorY = newSize.getHeight() / currentSize.getHeight();
        // and the pages should be centered instead of enlarged.
        if (noEnlarge) {
            if (factorX > 1) {
                factorX = 1;
            }
            if (factorY > 1) {
                factorY = 1;
            }
        }
        if (preserveAspectRatio) {
            factorX = Math.min(factorX, factorY);
            factorY = factorX;
        }
        offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f;
        offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f;
        page = writer.getImportedPage(currentReader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY);
    }
    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) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) PdfProcessingException(org.jaffa.modules.printing.services.exceptions.PdfProcessingException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) 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 7 with FormPrintException

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

the class VelocityTemplateHelper method renderTemplateLines.

public String[] renderTemplateLines() throws FormPrintException {
    String[] lines;
    String line;
    if (log.isDebugEnabled())
        log.debug("Begin Velocity template rendering process... ");
    if (getDataSource() == null) {
        log.debug("Data source is not set, returning.");
        return null;
    }
    if (getTemplate() == null) {
        log.debug("Template definition is not set, returning.");
        return null;
    }
    try {
        // Since Velocity can only be initialized one time, set the template path used by label printing.
        FormCache cache = new FormCache();
        String path = cache.getTemplatePath();
        Velocity.setProperty("file.resource.loader.path", path);
        Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
        // init the runtime engine.  Use mostly defaulted values.
        Velocity.init();
        if (log.isDebugEnabled()) {
            log.debug("Initialized Velocity");
            log.debug("Velocity file.resource.loader.path property = " + Velocity.getProperty("file.resource.loader.path"));
        }
    } catch (Exception e) {
        String err = "Velocity Initialization - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    }
    // make a Context and put data into it
    if (log.isDebugEnabled())
        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());
    if (log.isDebugEnabled()) {
        log.debug("*** Template Source Data = \n" + BeanMoulder.printBean(getDataSource()) + "\n*** End of Source Data.");
        log.debug("*** Velocity Template = \n" + getTemplate() + "\n*** End of Velocity Template.");
    }
    try {
        m_output = new StringWriter();
        if (log.isDebugEnabled())
            log.debug("Evaluate the Template... ");
        // Render the template
        Velocity.evaluate(context, m_output, "formTemplate", getTemplate());
        line = m_output.toString();
        lines = line.split("\n");
        if (log.isDebugEnabled()) {
            log.debug("*** Rendered Template = \n" + line + "\n*** End of Rendered Template.");
        }
    } catch (Exception e) {
        String err = "Velocity Error - " + e.getLocalizedMessage();
        log.error(err, e);
        throw new EngineProcessingException(err, e);
    }
    if (log.isDebugEnabled())
        log.debug("Finished Velocity template rendering process. ");
    return lines;
}
Also used : FormCache(org.jaffa.modules.printing.services.FormCache) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) 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)

Example 8 with FormPrintException

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

the class FormPrintEngineIText method initEngine.

/**
 * Perform any initialization activity for generating the document
 * @throws FormPrintException Thrown if there were initialization errors
 */
protected void initEngine() throws FormPrintException {
    log.debug("initEngine:");
    if (getTemplateName() != null) {
        if (!(new File(getTemplateName())).exists()) {
            FormPrintException e = new EngineProcessingException("Form Template Not Found", new FileNotFoundException(getTemplateName()));
            log.error("Form Template Not Found." + getTemplateName(), e);
            throw e;
        }
    } else {
        FormPrintException e = new EngineProcessingException("Form Template Name Missing.");
        log.error(" Form Template Name Missing. ");
        throw e;
    }
}
Also used : FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) 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