List of usage examples for com.lowagie.text.pdf AcroFields getFields
public HashMap getFields()
From source file:buckley.extract.Extractor.java
License:Apache License
public Document extract(InputStream input) { Document document = new Document(); PdfReader pdfReader = pdfReaderFactory.build(input); AcroFields acroFields = pdfReader.getAcroFields(); if (acroFields == null) throw new IllegalStateException("No form found on pdf"); HashMap fields = acroFields.getFields(); for (Object key : fields.keySet()) { String fieldName = (String) key; int[] pageNumbers = pageNumberEvaluator.getPages(acroFields.getFieldPositions(fieldName)); int fieldCount = 0; for (int pageNumber : pageNumbers) { Field field = fieldFactory.build(acroFields.getFieldType(fieldName)); field.setName(fieldName);//from w w w. j a v a2 s.c o m Page page = document.getPage(pageNumber); if (page == null) { page = new Page(pageNumber); document.addPage(page); } for (ITextFieldExtractor fieldExtractor : fieldExtractors) { if (fieldExtractor.canExtract(field)) { fieldExtractor.extract(fieldCount, field, fieldName, acroFields); } } page.addField(field); fieldCount++; } } return document; }
From source file:classroom.newspaper_b.Newspaper11.java
@SuppressWarnings("unchecked") public static void main(String[] args) { try {/* ww w .j a v a 2 s . c o m*/ PdfReader reader = new PdfReader(NEWSPAPER); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); PdfContentByte canvas = stamper.getOverContent(1); canvas.setRGBColorFill(0xFF, 0xFF, 0xFF); canvas.rectangle(LLX1, LLY1, W1, H1); canvas.rectangle(LLX2, LLY2, W2, H2); canvas.fill(); addTextField(stamper, new Rectangle(LLX1, LLY1, URX1, URY1), "field1", 1); addTextField(stamper, new Rectangle(LLX2, LLY2, URX2, URY2), "field2", 1); stamper.close(); reader = new PdfReader(RESULT); AcroFields fields = reader.getAcroFields(); Set<String> fieldnames = fields.getFields().keySet(); for (String fieldname : fieldnames) { System.out.print(fieldname); System.out.print(": page "); float[] positions = fields.getFieldPositions(fieldname); System.out.print(positions[0]); System.out.print(" [ "); System.out.print(positions[1]); System.out.print(", "); System.out.print(positions[2]); System.out.print(", "); System.out.print(positions[3]); System.out.print(", "); System.out.print(positions[4]); System.out.println("]"); } } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:com.bluexml.side.Framework.alfresco.workflow.pdfGenerator.generate.extract.ExtractDataFromPDF.java
License:Open Source License
public static HashMap<String, String> extractData(PdfReader reader) { HashMap<String, String> data = new HashMap<String, String>(); AcroFields form = reader.getAcroFields(); HashMap<String, Item> fields = form.getFields(); Set<String> fieldsNames = fields.keySet(); for (String fieldName : fieldsNames) { data.put(fieldName, form.getField(fieldName)); }/*from w w w . j a v a 2 s .c o m*/ return data; }
From source file:corner.orm.tapestry.pdf.PdfTemplateParser.java
License:Apache License
/** * reader??pdf.//from ww w. ja v a2s . co m * * @param reader * pdf reader */ void parse() { AcroFields form = reader.getAcroFields(); HashMap fields = form.getFields(); for (Iterator i = fields.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); switch (form.getFieldType(key)) { case AcroFields.FIELD_TYPE_TEXT: // TextField? if (PAGE_CLASS_DEFINE_FIELD_NAME.equals(key)) { this.pageClass = form.getField(key); break; } float[] p = form.getFieldPositions(key); int step = 5; int num = p.length / step; for (int j = 0; j < num; j++) { //??? PdfBlock block = new PdfBlock();// createBlockByName(key); if (block == null) { break; } block.setPosition(new float[] { p[j * step], p[j * step + 1], p[j * step + 2], p[j * step + 3], p[j * step + 4] }); block.setName(key); block.setValue(form.getField(key)); int pageNum = block.getPageNum(); List<PdfBlock> pagefs = pageFields.get(pageNum); if (pagefs == null) { pagefs = new ArrayList<PdfBlock>(); pageFields.put(pageNum, pagefs); } pagefs.add(block); } break; default: break; } } }
From source file:hornet.framework.export.fdf.FDF.java
License:CeCILL license
/** * Thread-safe utility method for PDF generation, based on a FDF template stream and a data object to * merge. Fields defined in FDF that can't be merged (not corresponding field in data object) are stored * in FDF Result.//from w w w . j ava 2 s .c om * * @param in * input stream of PDF/FDF (template) * @param out * output stream of final PDF * @param data * a javabean or a java.util.Map. Nested properties are allowed this field names access pattern * : "propA:propB:propC". * @return FDF result object (not null) */ public static FDFRes export(final InputStream in, final OutputStream out, final Object data) { PdfReader pdfIn = null; PdfStamper stamper = null; final FDFRes res = new FDFRes(); try { pdfIn = new PdfReader(in); stamper = new PdfStamper(pdfIn, out); final AcroFields form = stamper.getAcroFields(); // fusion champs FDF avec le bean for (final Object nomField : form.getFields().keySet()) { fusionChamp(data, stamper, res, form, nomField); } // la ligne suivante supprime le formulaire stamper.setFormFlattening(true); } catch (final IOException ex) { throw new FDFExportException(ex); } catch (final DocumentException ex) { throw new FDFExportException(ex); } finally { try { stamper.close(); } catch (final Exception ex) { LOG.error("Erreur", ex); } } return res; }
From source file:it.jugpadova.blo.ParticipantBadgeBo.java
License:Apache License
protected int getParticipantsPerPage(Event event) throws IOException { int count = 0; InputStream templateIs = getBadgePageTemplateInputStream(event); RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs); PdfReader template = new PdfReader(rafa, null); AcroFields form = template.getAcroFields(); HashMap fields = form.getFields(); while (true) { if (fields.containsKey("firstName" + (count + 1))) { count++;//from w ww . j a v a 2s.c o m } else { break; } } template.close(); return count; }
From source file:org.apache.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * *//*ww w. jav a 2 s .c o m*/ 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)); 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 (GenericEntityException e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (GeneralException e) { Debug.logError(e, "Error generating PDF: " + e.getMessage(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } catch (Exception 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; }
From source file:org.apache.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * *///from w w w. ja v a 2 s .co m 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 || surveyQuestionTypeId.equals("TEXT_SHORT")) { surveyResponseAnswer.set("textResponse", value); } delegator.create(surveyResponseAnswer); } s.close(); } catch (GenericEntityException e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (GeneralException e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } catch (Exception 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; }
From source file:org.apache.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** *//*from ww w.ja va 2s . co m*/ public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) { Map<String, Object> acroFieldMap = new HashMap<String, Object>(); 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 e) { System.err.println(e.getMessage()); return ServiceUtil.returnError(e.getMessage()); } catch (GeneralException e) { System.err.println(e.getMessage()); return ServiceUtil.returnError(e.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); return ServiceUtil.returnError(ioe.getMessage()); } Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("acroFieldMap", acroFieldMap); return results; }
From source file:org.apache.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** *///from ww w . j a v a 2s . c om public static Map<String, Object> setAcroFields(DispatchContext dctx, Map<String, ? extends Object> context) { Map<String, Object> results = ServiceUtil.returnSuccess(); Delegator delegator = dctx.getDelegator(); try { Map<String, Object> acroFieldMap = UtilGenerics.checkMap(context.get("acroFieldMap")); ByteBuffer byteBuffer = getInputByteBuffer(context, delegator); PdfReader r = new PdfReader(byteBuffer.array()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfStamper s = new PdfStamper(r, baos); AcroFields fs = s.getAcroFields(); Map<String, Object> map = UtilGenerics.checkMap(fs.getFields()); s.setFormFlattening(true); for (String fieldName : map.keySet()) { String fieldValue = fs.getField(fieldName); Object obj = acroFieldMap.get(fieldName); if (obj instanceof Date) { Date d = (Date) obj; fieldValue = UtilDateTime.toDateString(d); } else if (obj instanceof Long) { Long lg = (Long) obj; fieldValue = lg.toString(); } else if (obj instanceof Integer) { Integer ii = (Integer) obj; fieldValue = ii.toString(); } else { fieldValue = (String) obj; } if (UtilValidate.isNotEmpty(fieldValue)) { fs.setField(fieldName, fieldValue); } } s.close(); baos.close(); ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray()); results.put("outByteBuffer", outByteBuffer); } catch (DocumentException e) { System.err.println(e.getMessage()); results = ServiceUtil.returnError(e.getMessage()); } catch (GeneralException e) { System.err.println(e.getMessage()); results = ServiceUtil.returnError(e.getMessage()); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); results = ServiceUtil.returnError(e.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); results = ServiceUtil.returnError(ioe.getMessage()); } catch (Exception ioe) { System.err.println(ioe.getMessage()); results = ServiceUtil.returnError(ioe.getMessage()); } return results; }