List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:org.obiba.onyx.marble.engine.MarbleModule.java
License:Open Source License
public String getConsentField(Consent consent, String fieldName) { byte[] pdfForm = consent.getPdfForm(); // Access PDF content with IText library. PdfReader reader;//w ww .j a v a 2s. c om try { reader = new PdfReader(pdfForm); } catch (IOException ex) { throw new RuntimeException(ex); } // Get the PDF form fields. AcroFields form = reader.getAcroFields(); return form.getField(fieldName); }
From source file:org.obiba.onyx.print.impl.DefaultPdfTemplateEngine.java
License:Open Source License
public InputStream applyTemplate(Locale locale, Map<String, String> fieldToVariableMap, LocalizedResourceLoader reportTemplateLoader, ActiveInterviewService activeInterviewService) { // Get report template Resource resource = reportTemplateLoader.getLocalizedResource(locale); // Read report template PdfReader pdfReader;/*from w ww . j a v a2s . c om*/ try { pdfReader = new PdfReader(resource.getInputStream()); } catch (Exception ex) { throw new RuntimeException("Report to participant template cannot be read", ex); } ByteArrayOutputStream output = new ByteArrayOutputStream(); PdfStamper stamper = null; // Set the values in the report data fields try { stamper = new PdfStamper(pdfReader, output); stamper.setFormFlattening(true); AcroFields form = stamper.getAcroFields(); Participant participant = activeInterviewService.getParticipant(); setVariableDataFields(participant, form, fieldToVariableMap, locale); setAdditionalDataFields(form); } catch (Exception ex) { throw new RuntimeException("An error occured while preparing the report to participant", ex); } finally { try { stamper.close(); } catch (Exception e) { log.warn("Could not close PdfStamper", e); } try { output.close(); } catch (IOException e) { log.warn("Could not close OutputStream", e); } pdfReader.close(); } return new ByteArrayInputStream(output.toByteArray()); }
From source file:org.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"); String oooHost = (String) context.get("oooHost"); String oooPort = (String) context.get("oooPort"); GenericValue userLogin = (GenericValue) context.get("userLogin"); try {//from w ww . j a v a 2 s . c o m List<EntityCondition> exprList = FastList.newInstance(); 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); //Rectangle rect = document.getPageSize(); //PdfWriter writer = PdfWriter.getInstance(document, baos); PdfCopy writer = new PdfCopy(document, baos); document.open(); int pgCnt = 0; for (GenericValue contentAssocRevisionItemView : compDocParts) { //String thisContentId = contentAssocRevisionItemView.getString("contentId"); //String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId"); 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 { ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin, "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType", "application/pdf"); if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost); if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort); Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer", convertInMap); if (ServiceUtil.isError(convertResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale), null, null, convertResult); } ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } if (reader != null) { int n = reader.getNumberOfPages(); for (int i = 0; i < n; i++) { PdfImportedPage pg = writer.getImportedPage(reader, i + 1); //cb.addTemplate(pg, left, height * pgCnt); 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.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * */// w w w .j a va 2s. 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?) /*String[] listOptionDisplayArray = acroFields.getListOptionDisplay(fieldName); String[] listOptionExportArray = acroFields.getListOptionExport(fieldName); Debug.logInfo("listOptionDisplayArray: " + listOptionDisplayArray + "; listOptionExportArray: " + listOptionExportArray, module);*/ } 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 /* Interesting... this doesn't work, I guess we have to iterate to find the stuff... PdfObject typeValue = dict.get(new PdfName("/Type")); if (typeValue != null && "/Annot".equals(typeValue.toString())) { PdfObject tuValue = dict.get(new PdfName("/TU")); annotation = tuValue.toString(); } */ 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; } //Debug.logInfo("AcroForm widget fieldName[" + fieldName + "] dictKey[" + dictKeyName.toString() + "] dictValue[" + dictObject.toString() + "]", module); } 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.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * *///from w w w. ja v 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"); //String contentId = (String)context.get("contentId"); 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); //int type = fs.getFieldType(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.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** *//*from w w w. j a v a2 s . c o m*/ public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) { Map<String, Object> acroFieldMap = FastMap.newInstance(); 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); // Debug code to get the values for setting TDP // String[] sa = fs.getAppearanceStates("TDP"); // for (int i=0;i<sa.length;i++) // Debug.logInfo("Appearance="+sa[i]); 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.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** *//*w w w .j av a 2s. c o m*/ 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); // Debug code to get the values for setting TDP // String[] sa = fs.getAppearanceStates("TDP"); // for (int i=0;i<sa.length;i++) // Debug.logInfo("Appearance="+sa[i]); 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.openbravo.erpCommon.utility.reporting.printing.PrintController.java
License:Open Source License
private void concatReport(Report[] reports, HttpServletResponse response) { try {/* w w w .j a va2s . co m*/ int pageOffset = 0; // ArrayList master = new ArrayList(); int f = 0; String filename = ""; Report outFile = null; if (reports.length == 1) filename = reports[0].getFilename(); Document document = null; PdfCopy writer = null; while (f < reports.length) { if (filename == null || filename.equals("")) { outFile = reports[f]; if (multiReports) { filename = outFile.getTemplateInfo().getReportFilename(); filename = filename.replaceAll("@our_ref@", ""); filename = filename.replaceAll("@cus_ref@", ""); filename = filename.replaceAll(" ", "_"); filename = filename.replaceAll("-", ""); filename = filename + ".pdf"; } else { filename = outFile.getFilename(); } } response.setHeader("Content-disposition", "attachment" + "; filename=" + filename); // we create a reader for a certain document PdfReader reader = new PdfReader(reports[f].getTargetLocation()); reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); pageOffset += n; if (f == 0) { // step 1: creation of a document-object document = new Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, response.getOutputStream()); // step 3: we open the document document.open(); } // step 4: we add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } if (reports[f].isDeleteable()) { File file = new File(reports[f].getTargetLocation()); if (file.exists() && !file.isDirectory()) { file.delete(); } } f++; } document.close(); } catch (Exception e) { log4j.error(e); } }
From source file:org.openconcerto.erp.core.finance.accounting.report.PdfGenerator.java
License:Open Source License
private void init() throws FileNotFoundException { // we create a reader for a certain document PdfReader reader = null;/* ww w. j av a 2 s.co m*/ PdfWriter writer = null; try { reader = new PdfReader(getStreamStatic(this.fileNameIn)); // we retrieve the total number of pages int n = reader.getNumberOfPages(); // we retrieve the size of the first page Rectangle psize = reader.getPageSize(1); psize.setRight(psize.getRight() - this.templateOffsetX); psize.setTop(psize.getTop() - this.templateOffsetY); this.width = (int) psize.getWidth(); float height = psize.getHeight(); // step 1: creation of a document-object int MARGIN = 32; this.document = new Document(psize, MARGIN, MARGIN, MARGIN, MARGIN); // step 2: we create a writer that listens to the document if (!this.directoryOut.exists()) { this.directoryOut.mkdirs(); } System.err.println("Directory out " + this.directoryOut.getAbsolutePath()); File f = new File(this.directoryOut, this.fileNameOut); if (f.exists()) { f.renameTo(new File(this.directoryOut, "Old" + this.fileNameOut)); f = new File(this.directoryOut, this.fileNameOut); } System.err.println("Creation du fichier " + f.getAbsolutePath()); writer = PdfWriter.getInstance(this.document, new FileOutputStream(f)); this.document.open(); // step 4: we add content this.cb = writer.getDirectContent(); System.out.println("There are " + n + " pages in the document."); this.document.newPage(); PdfImportedPage page1 = writer.getImportedPage(reader, 1); this.cb.addTemplate(page1, -this.templateOffsetX, -this.templateOffsetY); this.bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED); this.bfb = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED); } catch (FileNotFoundException fE) { throw fE; } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } }
From source file:org.openconcerto.erp.core.finance.accounting.report.PDFImageInsertor.java
License:Open Source License
public void insert(File pdf, Image img, int page, boolean under) throws Exception { PdfReader reader;//from w ww .j a va 2 s. c o m reader = new PdfReader(new FileInputStream(pdf)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdf)); // img.setAbsolutePosition(20, 40); // int total = reader.getNumberOfPages() + 1; PdfContentByte content; if (under) { content = stamper.getUnderContent(page); } else { content = stamper.getOverContent(page); } content.addImage(img); stamper.close(); }