use of com.lowagie.text.DocumentException in project ofbiz-framework by apache.
the class PdfSurveyServices method getAcroFieldsFromPdf.
/**
*/
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> acroFieldMap = new HashMap<>();
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Delegator delegator = dctx.getDelegator();
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader r = new PdfReader(byteBuffer.array());
PdfStamper s = new PdfStamper(r, os);
AcroFields fs = s.getAcroFields();
Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
s.setFormFlattening(true);
for (String fieldName : map.keySet()) {
String parmValue = fs.getField(fieldName);
acroFieldMap.put(fieldName, parmValue);
}
} catch (DocumentException | GeneralException | IOException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("acroFieldMap", acroFieldMap);
return results;
}
use of com.lowagie.text.DocumentException in project ofbiz-framework by apache.
the class PdfSurveyServices method buildSurveyFromPdf.
/**
*/
public static Map<String, Object> buildSurveyFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
String surveyId = null;
try {
String surveyName = (String) context.get("surveyName");
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader pdfReader = new PdfReader(byteBuffer.array());
PdfStamper pdfStamper = new PdfStamper(pdfReader, os);
AcroFields acroFields = pdfStamper.getAcroFields();
Map<String, Object> acroFieldMap = UtilGenerics.checkMap(acroFields.getFields());
String contentId = (String) context.get("contentId");
GenericValue survey = null;
surveyId = (String) context.get("surveyId");
if (UtilValidate.isEmpty(surveyId)) {
survey = delegator.makeValue("Survey", UtilMisc.toMap("surveyName", surveyName));
survey.set("surveyId", surveyId);
survey.set("allowMultiple", "Y");
survey.set("allowUpdate", "Y");
survey = delegator.createSetNextSeqId(survey);
surveyId = survey.getString("surveyId");
}
// create a SurveyQuestionCategory to put the questions in
Map<String, Object> createCategoryResultMap = dispatcher.runSync("createSurveyQuestionCategory", UtilMisc.<String, Object>toMap("description", "From AcroForm in Content [" + contentId + "] for Survey [" + surveyId + "]", "userLogin", userLogin));
if (ServiceUtil.isError(createCategoryResultMap)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createCategoryResultMap));
}
String surveyQuestionCategoryId = (String) createCategoryResultMap.get("surveyQuestionCategoryId");
pdfStamper.setFormFlattening(true);
for (String fieldName : acroFieldMap.keySet()) {
AcroFields.Item item = acroFields.getFieldItem(fieldName);
int type = acroFields.getFieldType(fieldName);
String value = acroFields.getField(fieldName);
Debug.logInfo("fieldName:" + fieldName + "; item: " + item + "; value: " + value, module);
GenericValue surveyQuestion = delegator.makeValue("SurveyQuestion", UtilMisc.toMap("question", fieldName));
String surveyQuestionId = delegator.getNextSeqId("SurveyQuestion");
surveyQuestion.set("surveyQuestionId", surveyQuestionId);
surveyQuestion.set("surveyQuestionCategoryId", surveyQuestionCategoryId);
if (type == AcroFields.FIELD_TYPE_TEXT) {
surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
} else if (type == AcroFields.FIELD_TYPE_RADIOBUTTON) {
surveyQuestion.set("surveyQuestionTypeId", "OPTION");
} else if (type == AcroFields.FIELD_TYPE_LIST || type == AcroFields.FIELD_TYPE_COMBO) {
surveyQuestion.set("surveyQuestionTypeId", "OPTION");
// TODO: handle these specially with the acroFields.getListOptionDisplay (and getListOptionExport?)
} else {
surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
Debug.logWarning("Building Survey from PDF, fieldName=[" + fieldName + "]: don't know how to handle field type: " + type + "; defaulting to short text", module);
}
// ==== create a good sequenceNum based on tab order or if no tab order then the page location
Integer tabPage = item.getPage(0);
Integer tabOrder = item.getTabOrder(0);
Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder, module);
// array of float multiple of 5. For each of this groups the values are: [page, llx, lly, urx, ury]
float[] fieldPositions = acroFields.getFieldPositions(fieldName);
float fieldPage = fieldPositions[0];
float fieldLlx = fieldPositions[1];
float fieldLly = fieldPositions[2];
float fieldUrx = fieldPositions[3];
float fieldUry = fieldPositions[4];
Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry, module);
Long sequenceNum = null;
if (tabPage != null && tabOrder != null) {
sequenceNum = Long.valueOf(tabPage.intValue() * 1000 + tabOrder.intValue());
Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder + ", sequenceNum=" + sequenceNum, module);
} else if (fieldPositions.length > 0) {
sequenceNum = Long.valueOf((long) fieldPage * 10000 + (long) fieldLly * 1000 + (long) fieldLlx);
Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry + ", sequenceNum=" + sequenceNum, module);
}
// TODO: need to find something better to put into these fields...
String annotation = null;
for (int k = 0; k < item.size(); ++k) {
PdfDictionary dict = item.getWidget(k);
// if the "/Type" value is "/Annot", then get the value of "/TU" for the annotation
PdfObject typeValue = null;
PdfObject tuValue = null;
Set<PdfName> dictKeys = UtilGenerics.checkSet(dict.getKeys());
for (PdfName dictKeyName : dictKeys) {
PdfObject dictObject = dict.get(dictKeyName);
if ("/Type".equals(dictKeyName.toString())) {
typeValue = dictObject;
} else if ("/TU".equals(dictKeyName.toString())) {
tuValue = dictObject;
}
}
if (tuValue != null && typeValue != null && "/Annot".equals(typeValue.toString())) {
annotation = tuValue.toString();
}
}
surveyQuestion.set("description", fieldName);
if (UtilValidate.isNotEmpty(annotation)) {
surveyQuestion.set("question", annotation);
} else {
surveyQuestion.set("question", fieldName);
}
GenericValue surveyQuestionAppl = delegator.makeValue("SurveyQuestionAppl", UtilMisc.toMap("surveyId", surveyId, "surveyQuestionId", surveyQuestionId));
surveyQuestionAppl.set("fromDate", nowTimestamp);
surveyQuestionAppl.set("externalFieldRef", fieldName);
if (sequenceNum != null) {
surveyQuestionAppl.set("sequenceNum", sequenceNum);
}
surveyQuestion.create();
surveyQuestionAppl.create();
}
pdfStamper.close();
if (UtilValidate.isNotEmpty(contentId)) {
survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
survey.set("acroFormContentId", contentId);
survey.store();
}
} 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("surveyId", surveyId);
return results;
}
use of com.lowagie.text.DocumentException in project polymap4-core by Polymap4.
the class PDFMapResponse method formatImageOutputStream.
/**
* Writes the PDF.
* <p>
* NOTE: the document seems to actually be created in memory, and being written
* down to {@code output} once we call {@link Document#close()}. If there's no
* other way to do so, it'd be better to actually split out the process into
* produceMap/write?
* </p>
*
* @see org.geoserver.ows.Response#write(java.lang.Object, java.io.OutputStream,
* org.geoserver.platform.Operation)
*/
@Override
public void formatImageOutputStream(RenderedImage image, OutputStream out, WMSMapContent mapContent) throws ServiceException, IOException {
final int width = mapContent.getMapWidth();
final int height = mapContent.getMapHeight();
log.debug("setting up " + width + "x" + height + " image");
try {
// step 1: creation of a document-object
// width of document-object is width*72 inches
// height of document-object is height*72 inches
com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height);
Document document = new Document(pageSize);
document.setMargins(0, 0, 0, 0);
// step 2: creation of the writer
PdfWriter writer = PdfWriter.getInstance(document, out);
// step 3: we open the document
document.open();
// step 4: we grab the ContentByte and do some stuff with it
// we create a fontMapper and read all the fonts in the font
// directory
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
// we create a template and a Graphics2D object that corresponds
// with it
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper);
// we set graphics options
if (!mapContent.isTransparent()) {
graphic.setColor(mapContent.getBgColor());
graphic.fillRect(0, 0, width, height);
} else {
if (log.isDebugEnabled()) {
log.debug("setting to transparent");
}
int type = AlphaComposite.SRC;
graphic.setComposite(AlphaComposite.getInstance(type));
Color c = new Color(mapContent.getBgColor().getRed(), mapContent.getBgColor().getGreen(), mapContent.getBgColor().getBlue(), 0);
graphic.setBackground(mapContent.getBgColor());
graphic.setColor(c);
graphic.fillRect(0, 0, width, height);
type = AlphaComposite.SRC_OVER;
graphic.setComposite(AlphaComposite.getInstance(type));
}
// Rectangle paintArea = new Rectangle(width, height);
// Envelope dataArea = mapContent.getRenderingArea();
graphic.drawImage(PlanarImage.wrapRenderedImage(image).getAsBufferedImage(), 0, 0, width, height, null);
graphic.dispose();
cb.addTemplate(tp, 0, 0);
// step 5: we close the document
document.close();
writer.flush();
writer.close();
} catch (DocumentException t) {
throw new ServiceException("Error setting up the PDF", t, "internalError");
}
}
use of com.lowagie.text.DocumentException in project beast-mcmc by beast-dev.
the class MapperFrameOld method doExportPDF.
public final void doExportPDF() {
FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
Rectangle2D bounds = mapperPanel.getExportableComponent().getBounds();
Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
try {
// step 2
PdfWriter writer;
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper());
mapperPanel.getExportableComponent().print(g2d);
g2d.dispose();
cb.addTemplate(tp, 0, 0);
} catch (DocumentException de) {
JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error", JOptionPane.ERROR_MESSAGE);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error", JOptionPane.ERROR_MESSAGE);
}
document.close();
}
}
use of com.lowagie.text.DocumentException 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();
}
Aggregations