use of org.jaffa.modules.printing.services.exceptions.EngineProcessingException in project jaffa-framework by jaffa-projects.
the class FormPrintEnginePdfLib method writeForm.
/**
* Write the PDF to a specified file
* @param fileout file handle to use to write out the pdf
* @throws FormPrintException thrown if any pdf access error occurs
* @return return the file handle to the file that was written containing
* the generated PDF document. This will be null if there were any
* write errors.
*/
public File writeForm(File fileout) throws FormPrintException {
if (!isProcessed())
throw new IllegalStateException("The form not been processed yet");
try {
if (fileout == null)
fileout = File.createTempFile("form_", ".pdf");
OutputStream bos = new FileOutputStream(fileout);
bos.write(m_pdf.get_buffer());
bos.flush();
bos.close();
if (log.isDebugEnabled())
log.debug("PDFLib wrote out form " + fileout.getAbsolutePath());
} catch (IOException e) {
log.error("Error Reading Uploaded File", e);
return null;
} catch (PDFlibException e) {
log.error("PDFlibException: " + m_pdf.get_errmsg());
throw new EngineProcessingException(m_pdf.get_errmsg());
}
return fileout;
}
use of org.jaffa.modules.printing.services.exceptions.EngineProcessingException 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);
}
}
use of org.jaffa.modules.printing.services.exceptions.EngineProcessingException in project jaffa-framework by jaffa-projects.
the class FormPrintEngineIText method parseTemplatePages.
/**
* Process the template and do the following
* <ol>
* <li>Throw errors if there is something wrong with the template (in getTemplateName())
* <li>Determine to the total number of pages in the template
* (The template should have at least one page)
* <li>Populate an array where each template page should have one entry in it.
* Each entry will a PageDetails object, containing a list of fields
* on the page, and a list of repeating entities.
* </ol>
* On return from this the engine will calculate the total no of template pages,
* and the unique list of reappearing group names
* @throws FormPrintException Thrown if there is an error parsing the template pdf
* @return This returns a List of PageDetails objects which contain data about
* each page. It is assumed that the size of the list indicated the
* number of pages in the template document being used
*/
protected List parseTemplatePages() throws FormPrintException {
log.debug("parseTemplatePages:");
try {
m_templateReader = new PdfReader(getTemplateName());
} catch (IOException e) {
log.error("Error opening template - " + e.getMessage(), e);
throw new EngineProcessingException("Error opening template - " + e.getMessage());
}
// we retrieve the total number of pages
int templatePages = m_templateReader.getNumberOfPages();
if (templatePages < 1)
throw new EngineProcessingException("Template Document has no pages!");
if (log.isDebugEnabled())
log.debug("Template '" + getTemplateName() + "' has " + templatePages + " page(s)");
// Create Empty array of page data
ArrayList pageData = new ArrayList();
for (int templatePage = 0; templatePage < templatePages; templatePage++) {
PageDetailsExtended page = new PageDetailsExtended();
pageData.add(page);
}
// Look for a related data file...
File data = new File(getTemplateName() + ".csv");
if (!data.exists()) {
log.warn("CSV Parse Error: No data file found for field layout");
} else {
// Read the file, and populate PageDetailsExtended
try (BufferedReader in = new BufferedReader(new FileReader(data))) {
String line;
int[] colOrder = null;
int row = 0;
while ((line = in.readLine()) != null) {
row++;
if (line.startsWith("#") || line.length() == 0)
// ignore commented out or blank lines.
continue;
String[] cols = line.split(",");
if (row == 1) {
// Must be first line, analyse column names....
colOrder = new int[cols.length];
for (int i = 0; i < cols.length; i++) {
String col = cols[i];
colOrder[i] = HEADINGS.indexOf(col);
if (colOrder[i] == -1) {
log.error("CSV Parse Error: Unknown column heading '" + col + "' in column " + (i + 1) + ". Can't Process File");
throw new EngineProcessingException("Can't read layout data file, column headings incorrect");
}
}
} else {
// This is a row of data, process it
int pageNo = 0;
String field = null;
FormPrintEngineIText.FieldProperties props = new FormPrintEngineIText.FieldProperties();
for (int i = 0; i < cols.length; i++) {
try {
if (cols[i] != null && cols[i].trim().length() > 0 && colOrder != null) {
String value = cols[i].trim();
switch(colOrder[i]) {
case COLUMN_PAGE:
pageNo = Integer.parseInt(value);
break;
case COLUMN_FIELD:
field = value;
break;
case COLUMN_X1:
props.x1 = Float.parseFloat(value);
break;
case COLUMN_Y1:
props.y1 = Float.parseFloat(value);
break;
case COLUMN_X2:
props.x2 = Float.parseFloat(value);
break;
case COLUMN_Y2:
props.y2 = Float.parseFloat(value);
break;
case COLUMN_FONT:
props.fontFace = value;
break;
case COLUMN_SIZE:
props.fontSize = Float.parseFloat(value);
break;
case COLUMN_ALIGN:
if ("center".equalsIgnoreCase(value)) {
props.align = Element.ALIGN_CENTER;
} else if ("right".equalsIgnoreCase(value)) {
props.align = Element.ALIGN_RIGHT;
}
break;
case COLUMN_MULTILINE:
props.multiLine = Boolean.valueOf(value).booleanValue();
break;
case COLUMN_FIT_METHOD:
if (FIT_METHODS.contains(value.toLowerCase()))
props.fitMethod = FIT_METHODS.indexOf(value.toLowerCase());
break;
case COLUMN_ROTATE:
props.rotate = Float.parseFloat(value);
break;
case COLUMN_STYLE:
props.style = value;
break;
case COLUMN_COLOR:
props.color = value;
break;
case COLUMN_BACKGROUND:
props.background = value;
break;
case COLUMN_SAMPLE_DATA:
props.sampleData = URLDecoder.decode(value, "UTF-8");
break;
case COLUMN_OPACITY:
props.opacity = Float.parseFloat(value);
break;
}
// switch
}
} catch (NumberFormatException ne) {
String err = "CSV Parse Error: Invalid Numeric Value in Form Layout Data. Row=" + row + ", Column=" + i + ", Value='" + cols[i] + "'";
log.error(err);
throw new EngineProcessingException(err);
}
}
// for
if (pageNo < 1 || pageNo > templatePages) {
String err = "CSV Parse Error: Invalid Page Number " + pageNo + " on row " + row;
log.error(err);
throw new EngineProcessingException(err);
}
if (field == null) {
String err = "CSV Parse Error: Invalid/Missing Field Name on row " + row;
log.error(err);
throw new EngineProcessingException(err);
}
PageDetailsExtended page = (PageDetailsExtended) pageData.get(pageNo - 1);
page.fieldList.add(field);
page.fieldProperties.put(field, props);
}
}
// while loop on each input line
} catch (IOException e) {
log.warn("CSV Parse Error: Failed to read layout data file", e);
}
}
return pageData;
}
use of org.jaffa.modules.printing.services.exceptions.EngineProcessingException in project jaffa-framework by jaffa-projects.
the class CustomDataBeanFactory method getInstance.
public IDataBean getInstance() throws FrameworkException, ApplicationExceptions {
// Construct the DataBean
IDataBean dataBean = null;
IAdditionalDataObject dataBean2 = null;
try {
log.debug("Created a Custom DataBean " + m_beanClass);
dataBean = (IDataBean) m_beanClass.newInstance();
if (m_beanClass.newInstance() instanceof IAdditionalDataObject) {
if (dataBean != null) {
dataBean2 = (IAdditionalDataObject) dataBean;
dataBean2.setAdditionalDataObject(additionalDataObject);
}
}
} catch (IllegalAccessException e) {
log.error("Can't create data bean", e);
throw new EngineProcessingException(e.getMessage(), e);
} catch (InstantiationException e) {
log.error("Can't create data bean", e);
throw new EngineProcessingException(e.getMessage(), e);
}
if (dataBean == null)
throw new EngineProcessingException("No CustomDataBean created");
// Populate the keys
if (m_keys != null) {
for (String field : m_keys.keySet()) {
String value = m_keys.get(field);
try {
BeanHelper.setField(dataBean, field, value);
} catch (IntrospectionException e) {
log.error("Can't set bean property " + field, e);
} catch (IllegalAccessException e) {
log.error("Can't set bean property " + field, e);
} catch (InvocationTargetException e) {
log.error("Can't set bean property " + field, e);
}
}
}
if (m_formName != null) {
try {
BeanHelper.setField(dataBean, "formName", m_formName);
} catch (IntrospectionException e) {
log.error("Can't set bean property formName. " + e);
} catch (IllegalAccessException e) {
log.error("Can't set bean property formName. " + e);
} catch (InvocationTargetException e) {
log.error("Can't set bean property formName. " + e);
}
}
// Now make sure the bean has data in it
dataBean.populate();
return dataBean;
}
use of org.jaffa.modules.printing.services.exceptions.EngineProcessingException in project jaffa-framework by jaffa-projects.
the class FormCache method getTemplate.
/**
* Get the template file out of the BLOB's, write them to a file, and
* return the path to that file.
* A temp location for this can be defined, and in this case it will
* cache them there and only read them from the database if they don't exist,
* or are older that the database time stamp.
*/
public String getTemplate(FormDefinition form, String engineType) throws FrameworkException {
String extn = ".tpl";
if (FormPrintFactory.ENGINE_TYPE_ITEXT.equals(engineType) || FormPrintFactory.ENGINE_TYPE_PDFLIB.equals(engineType)) {
extn = ".pdf";
} else if (FormPrintFactory.ENGINE_TYPE_FOP.equals(engineType)) {
extn = ".xslt";
}
File temp = new File(getTemplatePath(), form.getFormId() + extn);
// See if a cached version can be returned
if (temp.exists() && ((form.getLastChangedOn() == null && form.getCreatedOn() != null && temp.lastModified() > form.getCreatedOn().timeInMillis()) || (form.getLastChangedOn() != null && temp.lastModified() > form.getLastChangedOn().timeInMillis()))) {
// If this is itext, make sure the CSV file is also current
if (FormPrintFactory.ENGINE_TYPE_ITEXT.equals(engineType)) {
File tempCsv = new File(getTemplatePath(), form.getFormId() + extn + ".csv");
// See if a cached version can be returned
if (tempCsv.exists() && ((form.getLastChangedOn() == null && form.getCreatedOn() != null && tempCsv.lastModified() > form.getCreatedOn().timeInMillis()) || (form.getLastChangedOn() != null && tempCsv.lastModified() > form.getLastChangedOn().timeInMillis()))) {
log.debug("Use Cached Template/CSV :" + temp.getAbsolutePath());
return temp.getAbsolutePath();
}
} else {
log.debug("Use Cached Template :" + temp.getAbsolutePath());
return temp.getAbsolutePath();
}
}
// Extract this from the Database
FormTemplate formTemp = form.getFormTemplateObject();
if (formTemp == null)
return null;
// Write out the template file
if (temp.exists())
temp.delete();
if (formTemp.getTemplateData() != null) {
if (!temp.getParentFile().exists())
temp.getParentFile().mkdirs();
try {
if (FormPrintFactory.ENGINE_TYPE_FOP.equals(engineType)) {
InputStream xsltTransformer = URLHelper.getInputStream(XSLT_TRANSFORMER);
try {
// Do all necessary transformations to the form XSLT file
XmlTransformerUtil.transform(formTemp.getTemplateData(), xsltTransformer, temp);
} catch (TransformerException e) {
String err = "Failed to Transform and write the Form Template " + temp.getAbsolutePath();
log.error(err, e);
throw new EngineProcessingException(err, e);
}
} else {
try (FileOutputStream fos = new FileOutputStream(temp)) {
fos.write(formTemp.getTemplateData());
}
}
log.debug("Written Template File " + temp.getAbsolutePath());
} catch (IOException e) {
String err = "Failed to write Template File " + temp.getAbsolutePath();
log.error(err, e);
throw new EngineProcessingException(err, e);
}
} else {
log.warn("No Template In Form Definition " + form.getFormId() + "(Name=" + form.getFormName() + ",Alt=" + form.getFormAlternate() + ",Variation=" + form.getFormVariation() + ",Output" + form.getOutputType());
}
File tempLayout = null;
// If the engine type is itext, specify where the CSV file should be written
if (FormPrintFactory.ENGINE_TYPE_ITEXT.equals(engineType))
tempLayout = new File(getTemplatePath(), form.getFormId() + ".pdf.csv");
// See if there is layout data needed
if (tempLayout != null) {
if (tempLayout.exists())
tempLayout.delete();
if (formTemp.getLayoutData() != null) {
try (FileOutputStream fos = new FileOutputStream(tempLayout)) {
fos.write(formTemp.getLayoutData());
log.debug("Written Template Layout File " + tempLayout.getAbsolutePath());
} catch (IOException e) {
String err = "Failed to write Layout File " + tempLayout.getAbsolutePath();
log.error(err, e);
throw new EngineProcessingException(err, e);
}
}
}
// return the temp file
return temp.getAbsolutePath();
}
Aggregations