List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java
License:Open Source License
/** * construct a pdf document from pdf parts. * /*from w ww . ja v a 2 s .c o m*/ * @param files * list containing the pdf to assemble * @param properties * converter properties * @param fout * outputstream to write the new pdf * @param base_url * base url of the document * @param producer * producer of the pdf * * @throws CConvertException * if an error occured while reconstruct. */ public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } // end if else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; // step 1: creation of a document-object // set title/creator/author document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, out); // use pdf version 1.5 writer.setPdfVersion(PdfWriter.VERSION_1_3); // compress the pdf writer.setFullCompression(); // check if encryption is needed if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType); } // end if final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } // end if else if (base_url != null) { document.addTitle(base_url); } // end else if final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } // end if else { document.addCreator(IHtmlToPdfTransformer.VERSION); } // end else final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } // end if final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.add(new Meta("Producer", sproducer)); } // end if else { document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer))); } // end else // step 3: we open the document document.open(); } // end if PdfImportedPage page; for (int j = 0; j < n;) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } // end for } // end for document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext();) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i) .replaceAll("<pagecount>", "" + n); // text over the existing page final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false" .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } // end if else { reader = new PdfReader(tmp2.getAbsolutePath()); } // end else final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } // end if final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } // end if else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } // end else if (reason != null) { sap.setReason(reason); } // end if if (location != null) { sap.setLocation(location); } // end if stp.close(); oldOut.flush(); } // end if } // end try catch (final Exception e) { throw new CConvertException( "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } // end catch finally { try { tmp.delete(); } // end try catch (final Exception ignore) { } try { tmp2.delete(); } // end try catch (final Exception ignore) { } } // end finally }
From source file:org.apache.camel.dataformat.jasperreports.JasperReportsTestBase.java
License:Open Source License
protected Map<String, String> getPdfInfo(MockEndpoint mock) throws IOException { Exchange exchange = mock.getReceivedExchanges().get(0); byte[] bytes = exchange.getIn().getBody(byte[].class); // read and parse a pdf PdfReader reader = new PdfReader(bytes); return reader.getInfo(); }
From source file:org.apache.ofbiz.content.compdoc.CompDocServices.java
License:Apache License
public static Map<String, Object> renderCompDocPdf(DispatchContext dctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); String rootDir = (String) context.get("rootDir"); String webSiteId = (String) context.get("webSiteId"); String https = (String) context.get("https"); Delegator delegator = dctx.getDelegator(); String contentId = (String) context.get("contentId"); String contentRevisionSeqId = (String) context.get("contentRevisionSeqId"); GenericValue userLogin = (GenericValue) context.get("userLogin"); try {/*w w w . ja v a 2 s .co m*/ List<EntityCondition> exprList = new LinkedList<EntityCondition>(); exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId)); exprList.add( EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART")); exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId)); if (UtilValidate.isNotEmpty(contentRevisionSeqId)) { exprList.add(EntityCondition.makeCondition("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId)); } List<GenericValue> compDocParts = EntityQuery.use(delegator) .select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum") .from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate() .queryList(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); document.setPageSize(PageSize.LETTER); PdfCopy writer = new PdfCopy(document, baos); document.open(); int pgCnt = 0; for (GenericValue contentAssocRevisionItemView : compDocParts) { String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId"); GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", thisDataResourceId).queryOne(); String inputMimeType = null; if (dataResource != null) { inputMimeType = dataResource.getString("mimeTypeId"); } byte[] inputByteArray = null; PdfReader reader = null; if (inputMimeType != null && inputMimeType.equals("application/pdf")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); reader = new PdfReader(inputByteArray); } else if (inputMimeType != null && inputMimeType.equals("text/html")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); String s = new String(inputByteArray); Debug.logInfo("text/html string:" + s, module); continue; } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) { String surveyResponseId = dataResource.getString("relatedDetailId"); String surveyId = null; String acroFormContentId = null; GenericValue surveyResponse = null; if (UtilValidate.isNotEmpty(surveyResponseId)) { surveyResponse = EntityQuery.use(delegator).from("SurveyResponse") .where("surveyResponseId", surveyResponseId).queryOne(); if (surveyResponse != null) { surveyId = surveyResponse.getString("surveyId"); } } if (UtilValidate.isNotEmpty(surveyId)) { GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId) .queryOne(); if (survey != null) { acroFormContentId = survey.getString("acroFormContentId"); if (UtilValidate.isNotEmpty(acroFormContentId)) { // TODO: is something supposed to be done here? } } } if (surveyResponse != null) { if (UtilValidate.isEmpty(acroFormContentId)) { // Create AcroForm PDF Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId)); if (ServiceUtil.isError(survey2PdfResults)) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } else { // Fill in acroForm Map<String, Object> survey2AcroFieldResults = dispatcher.runSync( "setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId)); if (ServiceUtil.isError(survey2AcroFieldResults)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } } } else { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale)); } if (reader != null) { int n = reader.getNumberOfPages(); for (int i = 0; i < n; i++) { PdfImportedPage pg = writer.getImportedPage(reader, i + 1); writer.addPage(pg); pgCnt++; } } } document.close(); ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray()); Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("outByteBuffer", outByteBuffer); return results; } catch (GenericEntityException e) { return ServiceUtil.returnError(e.toString()); } catch (IOException e) { Debug.logError(e, "Error in CompDoc operation: ", module); return ServiceUtil.returnError(e.toString()); } catch (Exception e) { Debug.logError(e, "Error in CompDoc operation: ", module); return ServiceUtil.returnError(e.toString()); } }
From source file:org.apache.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * */// www . j av a 2s . co 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 ww w . j av a 2 s . c o 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 w w w . j a va2 s . com*/ 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 w w w . j a va2 s . com*/ 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; }
From source file:org.areasy.common.doclet.utilities.PDFUtility.java
License:Open Source License
/** * Inserts pages from a PDF file into the document. * * @param pdfFile The PDF file object./*from w w w . j a v a2s.c om*/ * @param pages The string with the page numbers. * @throws Exception */ public static void insertPdfPages(File pdfFile, String pages) throws Exception { PdfReader reader = new PdfReader(new FileInputStream(pdfFile)); if (pages != null && pages.length() > 0) { StringTokenizer tok = new StringTokenizer(pages, ","); boolean createPage = false; while (tok.hasMoreTokens()) { String token = tok.nextToken(); // Check if token is single page number or page range int dashPos = token.indexOf("-"); if (dashPos != -1) { // It's a page range try { int from = Integer.parseInt(token.substring(0, dashPos)); int to = Integer.parseInt(token.substring(dashPos + 1, token.length())); insertPdfPages(reader, from, to, createPage); } catch (NumberFormatException e) { DocletUtility.error("Invalid PDF page numbers: " + token, e); } } else { // It's a single page try { int no = Integer.parseInt(token); insertPdfPages(reader, no, no, createPage); } catch (NumberFormatException e) { DocletUtility.error("Invalid PDF page number: " + token, e); } } createPage = true; } } else { // By default, insert page 1 insertPdfPages(reader, 1, 1, false); } }
From source file:org.areasy.common.doclet.utilities.PDFUtility.java
License:Open Source License
/** * Inserts a PDF file into the document. *// ww w . jav a 2 s . c o m * @param pdfFile The PDF file object. * @throws Exception */ public static void insertPdfDocument(File pdfFile) throws Exception { PdfWriter writer = Document.getWriter(); PdfReader reader = new PdfReader(new FileInputStream(pdfFile)); for (int pageNo = 1; pageNo < reader.getNumberOfPages() + 1; pageNo++) { Document.newPage(); PdfImportedPage page = writer.getImportedPage(reader, pageNo); writer.getDirectContent().addTemplate(page, 0.94f, 0, 0, 0.94f, 0, 30.0f); } }
From source file:org.efaps.esjp.common.file.FileUtil_Base.java
License:Apache License
/** * @param _files pdfs to be combined into one file * @param _fileName name of the file to be generated * @param _paginate paginat or not/* w w w . j a v a 2 s.c om*/ * @return file * @throws EFapsException on error */ public File combinePdfs(final List<File> _files, final String _fileName, final boolean _paginate) throws EFapsException { File ret = null; if (_files.size() == 1) { ret = _files.get(0); } else { try { final List<InputStream> pdfs = new ArrayList<>(); for (final File file : _files) { pdfs.add(new FileInputStream(file)); } ret = getFile(_fileName, "pdf"); final OutputStream outputStream = new FileOutputStream(ret); final Document document = new Document(); try { final List<PdfReader> readers = new ArrayList<>(); int totalPages = 0; final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } final PdfSmartCopy copy = new PdfSmartCopy(document, outputStream); final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); document.open(); while (iteratorPDFReader.hasNext()) { final PdfReader pdfReader = iteratorPDFReader.next(); for (int i = 0; i < pdfReader.getNumberOfPages(); i++) { final PdfImportedPage importedPage = copy.getImportedPage(pdfReader, i + 1); copy.addPage(importedPage); if (_paginate) { LOG.debug("Missing page ", totalPages); } } } outputStream.flush(); document.close(); outputStream.close(); // CHECKSTYLE:OFF } catch (final Exception e) { // CHECKSTYLE:ON e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (final IOException ioe) { ioe.printStackTrace(); } } } catch (final FileNotFoundException e) { LOG.error("FileNotFoundException", e); } } return ret; }