List of usage examples for com.lowagie.text.pdf PdfDictionary get
public PdfObject get(PdfName key)
PdfObject
associated to the specified key. From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
private void setActionInBookmark(Bookmark bookmark, PdfDictionary action) { PdfObject dest;//from ww w . j a v a 2 s .c o m if (PdfName.GOTO.equals(PdfReader.getPdfObjectRelease(action.get(PdfName.S)))) { dest = PdfReader.getPdfObjectRelease(action.get(PdfName.D)); if (dest != null) { mapGotoBookmark(bookmark, dest); } } else if (PdfName.URI.equals(PdfReader.getPdfObjectRelease(action.get(PdfName.S)))) { bookmark.setType(BookmarkType.Uri); bookmark.setUri(((PdfString) PdfReader.getPdfObjectRelease(action.get(PdfName.URI))).toUnicodeString()); } else if (PdfName.GOTOR.equals(PdfReader.getPdfObjectRelease(action.get(PdfName.S)))) { bookmark.setRemoteDestination(true); PdfObject file = PdfReader.getPdfObjectRelease(action.get(PdfName.F)); if (file != null) { if (file.isString()) { String path = Ut.onWindowsReplaceBackslashWithSlash(((PdfString) file).toUnicodeString()); bookmark.setRemoteFilePath(path); } else if (file.isDictionary()) { file = PdfReader.getPdfObject(((PdfDictionary) file).get(PdfName.F)); if (file.isString()) { bookmark.setRemoteFilePath(((PdfString) file).toUnicodeString()); } } } dest = PdfReader.getPdfObjectRelease(action.get(PdfName.D)); if (dest != null) { if (dest.isString()) { bookmark.setNamedDestination(dest.toString()); } else if (dest.isName()) { bookmark.setNamedDestination(PdfName.decodeName(dest.toString())); bookmark.setNamedAsName(true); } else if (dest.isArray()) { PdfArray arr = (PdfArray) dest; PdfReader remoteReader; try { // File remoteFile = new File(bookmark.getRemoteFilePath()); // if (!remoteFile.isAbsolute()) { // File openedFile = new File(filePath); // String containingFolder = openedFile.getParent(); // String remotePath = containingFolder + File.separator + bookmark.getRemoteFilePath(); // remoteFile = new File(remotePath); // } File remoteFile = Ut.createAbsolutePath(new File(filePath), new File(bookmark.getRemoteFilePath())); remoteReader = new PdfReader(remoteFile.getCanonicalPath()); makeBookmarkParam(remoteReader, bookmark, arr, null); remoteReader.close(); } catch (IOException ex) { //System.out.println(ex.getMessage()); } finally { } } } PdfObject newWindow = PdfReader.getPdfObjectRelease(action.get(PdfName.NEWWINDOW)); if (newWindow != null) { bookmark.setNewWindow(((PdfBoolean) newWindow).booleanValue()); } } else if (PdfName.LAUNCH.equals(PdfReader.getPdfObjectRelease(action.get(PdfName.S)))) { bookmark.setType(BookmarkType.Launch); PdfObject file = PdfReader.getPdfObjectRelease(action.get(PdfName.F)); if (file == null) { file = PdfReader.getPdfObjectRelease(action.get(PdfName.WIN)); } if (file != null) { if (file.isString()) { bookmark.setFileToLaunch(((PdfString) file).toUnicodeString()); } else if (file.isDictionary()) { file = PdfReader.getPdfObjectRelease(((PdfDictionary) file).get(PdfName.F)); if (file.isString()) { bookmark.setFileToLaunch(((PdfString) file).toUnicodeString()); } } } } else if (PdfName.HIDE.equals(PdfReader.getPdfObjectRelease(action.get(PdfName.S)))) { bookmark.setType(BookmarkType.Hide); PdfObject annotation = PdfReader.getPdfObjectRelease(action.get(PdfName.T)); if (annotation != null) { if (annotation.isDictionary()) { } else if (annotation.isArray()) { } else if (annotation.isString()) { bookmark.setFieldNameToHide(((PdfString) annotation).toUnicodeString()); } } PdfBoolean hide = (PdfBoolean) PdfReader.getPdfObjectRelease(action.get(PdfName.H)); if (hide != null) { bookmark.setHide(hide.booleanValue()); } } else { bookmark.setType(BookmarkType.Unknown); } }
From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
private void setActionsRecursive(Bookmark bookmark, PdfDictionary action) { setActionInBookmark(bookmark, action); PdfObject next = PdfReader.getPdfObjectRelease(action.get(PdfName.NEXT)); if (next != null) { if (next.isArray()) { PdfArray actions = (PdfArray) next; for (int i = 0; i < actions.size(); i++) { Bookmark b = new Bookmark(); action = actions.getAsDict(i); setActionsRecursive(b, action); bookmark.addChainedBookmark(b); }//from w w w .j av a 2s . c o m } else if (next.isDictionary()) { Bookmark b = new Bookmark(); action = (PdfDictionary) next; setActionsRecursive(b, action); bookmark.addChainedBookmark(b); } } }
From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
private Bookmark bookmarkFromDictionary(PdfDictionary outline) { if (outline == null) { return null; }/*from w w w . j a va2 s . c om*/ Bookmark bookmark = new Bookmark(); PdfString title = (PdfString) PdfReader.getPdfObjectRelease(outline.get(PdfName.TITLE)); bookmark.setTitle(title.toUnicodeString()); PdfArray color = (PdfArray) PdfReader.getPdfObjectRelease(outline.get(PdfName.C)); if (color != null && color.size() == 3) { ByteBuffer out = new ByteBuffer(); out.append(color.getAsNumber(0).floatValue()).append(' '); out.append(color.getAsNumber(1).floatValue()).append(' '); out.append(color.getAsNumber(2).floatValue()); bookmark.setColor(new Color(color.getAsNumber(0).floatValue(), color.getAsNumber(1).floatValue(), color.getAsNumber(2).floatValue())); } PdfNumber style = (PdfNumber) PdfReader.getPdfObjectRelease(outline.get(PdfName.F)); if (style != null) { int f = style.intValue(); if ((f & 1) != 0) { bookmark.setItalic(true); } if ((f & 2) != 0) { bookmark.setBold(true); } } PdfNumber count = (PdfNumber) PdfReader.getPdfObjectRelease(outline.get(PdfName.COUNT)); if (count != null && count.intValue() < 0) { bookmark.setOpened(false); } else { bookmark.setOpened(true); } try { PdfObject dest = PdfReader.getPdfObjectRelease(outline.get(PdfName.DEST)); if (dest != null) { mapGotoBookmark(bookmark, dest); } else { PdfDictionary action = (PdfDictionary) PdfReader.getPdfObjectRelease(outline.get(PdfName.A)); if (action != null) { setActionsRecursive(bookmark, action); } else { bookmark.setType(BookmarkType.Unknown); } } } catch (Exception e) { //empty on purpose } return bookmark; }
From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
private void bookmarkDepth(Bookmark father, PdfDictionary outline) { Bookmark bookmark = null;// w w w . j a v a2s . com while (outline != null) { bookmark = bookmarkFromDictionary(outline); PdfDictionary first = (PdfDictionary) PdfReader.getPdfObjectRelease(outline.get(PdfName.FIRST)); if (first != null) { bookmarkDepth(bookmark, first); } father.add(bookmark); outline = (PdfDictionary) PdfReader.getPdfObjectRelease(outline.get(PdfName.NEXT)); } }
From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
private static int getNumber(PdfIndirectReference indirect) { PdfDictionary pdfObj = (PdfDictionary) PdfReader.getPdfObjectRelease(indirect); if (pdfObj.contains(PdfName.TYPE) && pdfObj.get(PdfName.TYPE).equals(PdfName.PAGES) && pdfObj.contains(PdfName.KIDS)) { PdfArray kids = (PdfArray) pdfObj.get(PdfName.KIDS); indirect = (PdfIndirectReference) kids.getPdfObject(0); }// w ww.j a v a2 s . c o m return indirect.getNumber(); }
From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
public ArrayList<AnnotationRect> getLinks(int currentPage, boolean convertNamedDestinations) { ArrayList<AnnotationRect> bookmarkLinks = new ArrayList<AnnotationRect>(); ArrayList links = null;/*from www . j a v a 2 s . c o m*/ if (reader != null) { if (convertNamedDestinations) { reader.consolidateNamedDestinations(); } links = reader.getAnnotations(currentPage); for (int i = 0; i < links.size(); i++) { AnnotationRect annoRect = new AnnotationRect(); Bookmark bookmark = new Bookmark(); PdfDictionary annot = (PdfDictionary) links.get(i); try { PdfObject dest = PdfReader.getPdfObjectRelease(annot.get(PdfName.DEST)); if (dest != null) { mapGotoBookmark(bookmark, dest); } else { PdfDictionary action = (PdfDictionary) PdfReader.getPdfObjectRelease(annot.get(PdfName.A)); if (action != null) { setActionsRecursive(bookmark, action); } else { bookmark.setType(BookmarkType.Unknown); } } } catch (Exception e) { //empty on purpose } PdfObject obj = (PdfObject) annot.get(PdfName.RECT); if (obj instanceof PdfArray) { PdfArray rc = (PdfArray) obj; annoRect.llx = (int) rc.getAsNumber(0).floatValue(); annoRect.lly = (int) rc.getAsNumber(1).floatValue(); annoRect.urx = (int) rc.getAsNumber(2).floatValue(); annoRect.ury = (int) rc.getAsNumber(3).floatValue(); } annoRect.bookmark = bookmark; bookmarkLinks.add(annoRect); } } return bookmarkLinks; }
From source file:net.sqs2.omr.master.sqm.PDFAttachmentExtractor.java
License:Apache License
@SuppressWarnings("unchecked") private static byte[] extractAttachmentFiles(PdfReader reader, String suffix) throws IOException { PdfDictionary catalog = reader.getCatalog(); PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES)); if (names != null) { PdfDictionary embFiles = (PdfDictionary) PdfReader .getPdfObject(names.get(new PdfName("EmbeddedFiles"))); if (embFiles != null) { HashMap<?, PdfObject> embMap = PdfNameTree.readTree(embFiles); for (Iterator<PdfObject> i = embMap.values().iterator(); i.hasNext();) { PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(i.next()); byte[] ret = unpackFile(reader, filespec, suffix); if (ret != null) { return ret; }/*from w w w .ja v a2s . co m*/ } } } for (int k = 1; k <= reader.getNumberOfPages(); ++k) { PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS)); if (annots == null) { continue; } for (Iterator<PdfObject> i = annots.listIterator(); i.hasNext();) { PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(i.next()); PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE)); if (!PdfName.FILEATTACHMENT.equals(subType)) { continue; } PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS)); byte[] ret = unpackFile(reader, filespec, suffix); if (ret != null) { return ret; } } } return null; }
From source file:net.sqs2.omr.master.sqm.PDFAttachmentExtractor.java
License:Apache License
/** * Unpacks a file attachment.// w w w . jav a2 s . c om * * @param reader * The object that reads the PDF document * @param filespec * The dictionary containing the file specifications * @param outPath * The path where the attachment has to be written * @throws IOException */ private static byte[] unpackFile(PdfReader reader, PdfDictionary filespec, String suffix) throws IOException { if (filespec == null) { return null; } PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE)); if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) { return null; } PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF)); if (ef == null) { return null; } PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F)); if (fn == null) { return null; } File fLast = new File(fn.toUnicodeString()); String filename = fLast.getName(); if (!filename.endsWith(suffix)) { return null; } PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F)); if (prs == null) { return null; } return PdfReader.getStreamBytes(prs); }
From source file:net.sqs2.omr.master.sqm.PDFAttachmentToSQMTranslator.java
License:Apache License
private static byte[] extractAttachmentFiles(PdfReader reader, String suffix) throws IOException { PdfDictionary catalog = reader.getCatalog(); PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES)); if (names != null) { PdfDictionary embFiles = (PdfDictionary) PdfReader .getPdfObject(names.get(new PdfName("EmbeddedFiles"))); if (embFiles != null) { HashMap<?, PdfObject> embMap = PdfNameTree.readTree(embFiles); for (Iterator<PdfObject> i = embMap.values().iterator(); i.hasNext();) { PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(i.next()); byte[] ret = unpackFile(reader, filespec, suffix); if (ret != null) { return ret; }//from ww w . ja va 2s. c om } } } for (int k = 1; k <= reader.getNumberOfPages(); ++k) { PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS)); if (annots == null) { continue; } for (Iterator<PdfObject> i = annots.listIterator(); i.hasNext();) { PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(i.next()); PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE)); if (!PdfName.FILEATTACHMENT.equals(subType)) { continue; } PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS)); byte[] ret = unpackFile(reader, filespec, suffix); if (ret != null) { return ret; } } } return null; }
From source file:org.apache.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * */// ww w. jav a 2 s . com 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; }