use of com.lowagie.text.DocumentException in project ofbiz-framework by apache.
the class PdfSurveyServices method buildSurveyResponseFromPdf.
/**
*/
public static Map<String, Object> buildSurveyResponseFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
String surveyResponseId = null;
Locale locale = (Locale) context.get("locale");
try {
Delegator delegator = dctx.getDelegator();
String partyId = (String) context.get("partyId");
String surveyId = (String) context.get("surveyId");
surveyResponseId = (String) context.get("surveyResponseId");
if (UtilValidate.isNotEmpty(surveyResponseId)) {
GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
} else {
surveyResponseId = delegator.getNextSeqId("SurveyResponse");
GenericValue surveyResponse = delegator.makeValue("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyId", surveyId, "partyId", partyId));
surveyResponse.set("responseDate", UtilDateTime.nowTimestamp());
surveyResponse.set("lastModifiedDate", UtilDateTime.nowTimestamp());
surveyResponse.create();
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader r = new PdfReader(byteBuffer.array());
PdfStamper s = new PdfStamper(r, os);
AcroFields fs = s.getAcroFields();
Map<String, Object> hm = UtilGenerics.checkMap(fs.getFields());
s.setFormFlattening(true);
for (String fieldName : hm.keySet()) {
// AcroFields.Item item = fs.getFieldItem(fieldName);
String value = fs.getField(fieldName);
GenericValue surveyQuestionAndAppl = EntityQuery.use(delegator).from("SurveyQuestionAndAppl").where("surveyId", surveyId, "externalFieldRef", fieldName).queryFirst();
if (surveyQuestionAndAppl == null) {
Debug.logInfo("No question found for surveyId:" + surveyId + " and externalFieldRef:" + fieldName, module);
continue;
}
String surveyQuestionId = (String) surveyQuestionAndAppl.get("surveyQuestionId");
String surveyQuestionTypeId = (String) surveyQuestionAndAppl.get("surveyQuestionTypeId");
GenericValue surveyResponseAnswer = delegator.makeValue("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyQuestionId", surveyQuestionId));
if (surveyQuestionTypeId == null || "TEXT_SHORT".equals(surveyQuestionTypeId)) {
surveyResponseAnswer.set("textResponse", value);
}
delegator.create(surveyResponseAnswer);
}
s.close();
} catch (GeneralException | DocumentException | IOException e) {
Debug.logError(e, "Error generating PDF: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale));
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("surveyResponseId", surveyResponseId);
return results;
}
use of com.lowagie.text.DocumentException in project ofbiz-framework by apache.
the class PdfSurveyServices method buildPdfFromSurveyResponse.
/**
*/
public static Map<String, Object> buildPdfFromSurveyResponse(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Delegator delegator = dctx.getDelegator();
Map<String, Object> results = ServiceUtil.returnSuccess();
String surveyResponseId = (String) context.get("surveyResponseId");
String contentId = (String) context.get("contentId");
String surveyId = null;
Document document = new Document();
try {
if (UtilValidate.isNotEmpty(surveyResponseId)) {
GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
}
if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
if (survey != null) {
String acroFormContentId = survey.getString("acroFormContentId");
if (UtilValidate.isNotEmpty(acroFormContentId)) {
context.put("contentId", acroFormContentId);
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", surveyResponseId).queryList();
for (GenericValue surveyResponseAnswer : responses) {
String value = null;
String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion").where("surveyQuestionId", surveyQuestionId).queryOne();
String questionType = surveyQuestion.getString("surveyQuestionTypeId");
// DEJ20060227 this isn't used, if needed in the future should get from SurveyQuestionAppl.externalFieldRef String fieldName = surveyQuestion.getString("description");
if ("OPTION".equals(questionType)) {
value = surveyResponseAnswer.getString("surveyOptionSeqId");
} else if ("BOOLEAN".equals(questionType)) {
value = surveyResponseAnswer.getString("booleanResponse");
} else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
Double num = surveyResponseAnswer.getDouble("numericResponse");
if (num != null) {
value = num.toString();
}
} else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
// not really a question; ingore completely
} else {
value = surveyResponseAnswer.getString("textResponse");
}
Chunk chunk = new Chunk(surveyQuestion.getString("question") + ": " + value);
Paragraph p = new Paragraph(chunk);
document.add(p);
}
ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
results.put("outByteBuffer", outByteBuffer);
} catch (GenericEntityException | DocumentException e) {
Debug.logError(e, module);
results = ServiceUtil.returnError(e.getMessage());
}
return results;
}
use of com.lowagie.text.DocumentException 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();
}
use of com.lowagie.text.DocumentException in project jaffa-framework by jaffa-projects.
the class FormPrintEngineIText method startDocument.
/**
* Any work to start off printing the document
* @throws FormPrintException Thrown if there is any form processing problems
*/
protected void startDocument() throws FormPrintException {
log.debug("startDocument:");
Rectangle r = m_templateReader.getPageSize(getCurrentTemplatePage());
log.debug("Page Size : t=" + r.getTop() + ",l=" + r.getLeft() + ",b=" + r.getBottom() + ",r=" + r.getRight() + ", rot=" + r.getRotation());
r = m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage());
log.debug("Page Size w/Rot: t=" + r.getTop() + ",l=" + r.getLeft() + ",b=" + r.getBottom() + ",r=" + r.getRight() + ", rot=" + r.getRotation());
m_generatedDoc = new Document(m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()));
// m_generatedDoc = new Document(m_templateReader.getPageSize(getCurrentTemplatePage()));
m_output = new ByteArrayOutputStream();
try {
m_writer = PdfWriter.getInstance(m_generatedDoc, m_output);
} catch (DocumentException e) {
log.error("Error Creating Writer - " + e.getMessage(), e);
throw new EngineProcessingException("Error Creating Writer - " + e.getMessage());
}
if (getDocumentProperties() != null) {
Properties dp = (Properties) getDocumentProperties().clone();
if (dp.getProperty(DOCUMENT_PROPERTY_TITLE) != null) {
m_generatedDoc.addTitle(dp.getProperty(DOCUMENT_PROPERTY_TITLE));
dp.remove(DOCUMENT_PROPERTY_TITLE);
}
if (dp.getProperty(DOCUMENT_PROPERTY_SUBJECT) != null) {
m_generatedDoc.addSubject(dp.getProperty(DOCUMENT_PROPERTY_SUBJECT));
dp.remove(DOCUMENT_PROPERTY_SUBJECT);
}
if (dp.getProperty(DOCUMENT_PROPERTY_KEYWORDS) != null) {
m_generatedDoc.addKeywords(dp.getProperty(DOCUMENT_PROPERTY_KEYWORDS));
dp.remove(DOCUMENT_PROPERTY_KEYWORDS);
}
if (dp.getProperty(DOCUMENT_PROPERTY_CREATOR) != null) {
m_generatedDoc.addCreator(dp.getProperty(DOCUMENT_PROPERTY_CREATOR, "Jaffa Print Engine"));
dp.remove(DOCUMENT_PROPERTY_CREATOR);
}
if (dp.getProperty(DOCUMENT_PROPERTY_AUTHOR) != null) {
m_generatedDoc.addAuthor(dp.getProperty(DOCUMENT_PROPERTY_AUTHOR));
dp.remove(DOCUMENT_PROPERTY_AUTHOR);
}
// loop through other properties and set them as header parameters
for (Enumeration en = dp.elements(); en.hasMoreElements(); ) {
Map.Entry e = (Map.Entry) en.nextElement();
if (e.getKey() != null && e.getValue() != null)
m_generatedDoc.addHeader(e.getKey().toString(), e.getValue().toString());
}
}
m_generatedDoc.addCreationDate();
m_generatedDoc.open();
}
use of com.lowagie.text.DocumentException in project vcell by virtualcell.
the class ITextWriter method writeStructure.
protected void writeStructure(Model model, Structure struct, Table structTable) throws DocumentException {
// If this structure has any reactions in it, add its name as a hyperlink to the reactions' list.
if (hasReactions(model, struct)) {
Paragraph linkParagraph = new Paragraph();
Font linkFont;
try {
BaseFont fontBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
linkFont = new Font(fontBaseFont, DEF_FONT_SIZE, Font.NORMAL, new java.awt.Color(0, 0, 255));
} catch (Exception e) {
linkFont = getFont();
e.printStackTrace();
}
linkParagraph.add(new Chunk(struct.getName(), linkFont).setLocalGoto(struct.getName()));
Cell structLinkCell = new Cell(linkParagraph);
structLinkCell.setBorderWidth(1);
structLinkCell.setHorizontalAlignment(Element.ALIGN_LEFT);
structTable.addCell(structLinkCell);
} else {
structTable.addCell(createCell(struct.getName(), getFont()));
}
StructureTopology structTopology = model.getStructureTopology();
if (struct instanceof Membrane) {
structTable.addCell(createCell("Membrane", getFont()));
Feature outsideFeature = structTopology.getOutsideFeature((Membrane) struct);
Feature insideFeature = structTopology.getInsideFeature((Membrane) struct);
structTable.addCell(createCell((insideFeature != null ? insideFeature.getName() : "N/A"), getFont()));
structTable.addCell(createCell((outsideFeature != null ? outsideFeature.getName() : "N/A"), getFont()));
} else {
structTable.addCell(createCell("Feature", getFont()));
String outsideStr = "N/A", insideStr = "N/A";
Membrane enclosingMem = (Membrane) structTopology.getParentStructure(struct);
if (enclosingMem != null) {
outsideStr = enclosingMem.getName();
}
// To do: retrieve the 'child' membrane here...
structTable.addCell(createCell(insideStr, getFont()));
structTable.addCell(createCell(outsideStr, getFont()));
}
}
Aggregations