List of usage examples for com.lowagie.text.pdf PdfStamper PdfStamper
public PdfStamper(PdfReader reader, OutputStream os) throws DocumentException, IOException
From source file:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionRemoveWatermark() throws PageException, IOException, DocumentException { required("pdf", "removeWatermark", "source", source); if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.setBackground(Color.BLACK); g.clearRect(0, 0, 1, 1);// ww w .j a va2 s .c o m Image img = Image.getInstance(bi, null, false); img.setAbsolutePosition(1, 1); PDFStruct doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output OutputStream os = null; if (!Util.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } try { int len = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); Set _pages = doc.getPages(); for (int i = 1; i <= len; i++) { if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue; PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i); PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0); cb.setGState(gs1); cb.addImage(img); } if (bookmarks != null) stamp.setOutlines(master); stamp.close(); } finally { Util.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!Util.isEmpty(name)) { pageContext.setVariable(name, new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password)); } } } }
From source file:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionSetInfo() throws PageException, IOException, DocumentException { required("pdf", "setInfo", "info", info); required("pdf", "getInfo", "source", source); PDFStruct doc = toPDFDocument(source, password, null); PdfReader pr = doc.getPdfReader();//from ww w. ja v a2 s . co m OutputStream os = null; try { if (destination == null) { if (doc.getResource() == null) throw engine.getExceptionUtil().createApplicationException( "source is not based on a resource, destination file is required"); destination = doc.getResource(); } else if (destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); PdfStamper stamp = new PdfStamper(pr, os = destination.getOutputStream()); HashMap moreInfo = new HashMap(); // Key[] keys = info.keys(); Iterator<Entry<Key, Object>> it = info.entryIterator(); Entry<Key, Object> e; while (it.hasNext()) { e = it.next(); moreInfo.put(engine.getStringUtil().ucFirst(e.getKey().getLowerString()), engine.getCastUtil().toString(e.getValue())); } // author Object value = info.get("author", null); if (value != null) moreInfo.put("Author", engine.getCastUtil().toString(value)); // keywords value = info.get("keywords", null); if (value != null) moreInfo.put("Keywords", engine.getCastUtil().toString(value)); // title value = info.get("title", null); if (value != null) moreInfo.put("Title", engine.getCastUtil().toString(value)); // subject value = info.get("subject", null); if (value != null) moreInfo.put("Subject", engine.getCastUtil().toString(value)); // creator value = info.get("creator", null); if (value != null) moreInfo.put("Creator", engine.getCastUtil().toString(value)); // trapped value = info.get("Trapped", null); if (value != null) moreInfo.put("Trapped", engine.getCastUtil().toString(value)); // Created value = info.get("Created", null); if (value != null) moreInfo.put("Created", engine.getCastUtil().toString(value)); // Language value = info.get("Language", null); if (value != null) moreInfo.put("Language", engine.getCastUtil().toString(value)); stamp.setMoreInfo(moreInfo); stamp.close(); } finally { Util.closeEL(os); pr.close(); } }
From source file:org.meveo.admin.action.billing.BillingAccountBean.java
License:Open Source License
public void generatePDF(long invoiceId) { Invoice invoice = invoiceService.findById(invoiceId); byte[] invoicePdf = invoice.getPdf(); FacesContext context = FacesContext.getCurrentInstance(); String invoiceFilename = null; BillingRun billingRun = invoice.getBillingRun(); invoiceFilename = invoice.getInvoiceNumber() + ".pdf"; if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) { invoiceFilename = "unvalidated-invoice.pdf"; }// w w w . j a v a 2 s .co m HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/pdf"); // fill in response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename); try { OutputStream os = response.getOutputStream(); Document document = new Document(PageSize.A4); if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) { // Add watemark image PdfReader reader = new PdfReader(invoicePdf); int n = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); PdfContentByte over = null; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); int i = 1; while (i <= n) { over = stamp.getOverContent(i); over.setGState(gs); over.beginText(); System.out.println("top=" + document.top() + ",bottom=" + document.bottom()); over.setTextMatrix(document.top(), document.bottom()); over.setFontAndSize(bf, 150); over.setColorFill(Color.GRAY); over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); over.endText(); i++; } stamp.close(); } else { os.write(invoicePdf); // fill in PDF with bytes } // contentType os.flush(); os.close(); context.responseComplete(); } catch (IOException e) { log.error("failed to generate PDF ", e); } catch (DocumentException e) { log.error("error in generation PDF ", e); } }
From source file:org.mnsoft.pdfocr.Wrapper.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private void mergePDFs(File foreground, File background, File newFile, String title, String subject, String keywords, String author, String creator) { log.debug("Merge " + foreground + " (FG) and " + background + " (BG) to " + newFile); final double threshold = ((Integer) StringUtility.StringToInteger(getAttribute("THRESHOLD"), 2)) .doubleValue();/*from w w w . j ava 2 s . c om*/ try { /* * Foreground: Original Image. * Background: OCR'd Text */ final PdfReader fg = new PdfReader(foreground.getAbsolutePath()); final PdfReader bg = new PdfReader(background.getAbsolutePath()); /* * Count pages for foreground and background */ final int fg_num_pages = fg.getNumberOfPages(); final int bg_num_pages = bg.getNumberOfPages(); if (fg_num_pages != bg_num_pages) { log.error( "! Foreground and background have different number of pages. This should really not happen."); } /* * The output document */ final PdfStamper fg_writer = new PdfStamper(fg, new FileOutputStream(newFile)); /* * Create a PdfTemplate from the first page of mark * (PdfImportedPage is derived from PdfTemplate) */ PdfImportedPage bg_page = null; for (int i = 0; i < fg_num_pages;) { ++i; System.out.print(" [" + i + "]"); final byte[] fg_page_content = fg.getPageContent(i); final byte[] bg_page_content = bg.getPageContent(i); final int bg_size = bg_page_content.length; final int fg_size = fg_page_content.length; /* * If we're not explicitly merging, we're merging * the document with itself only anyway. */ if (!"true".equals(getAttribute("mergefiles"))) { continue; } /* * Modification 20130904 * * We want to scan only what's not been generated by a number of * generators. So, until now, the generator of whom we wanted to * ignore files was ocr, i.e. the one we set ourselves. Now, we * have seen that when we run an OCR on a "pdf+text" file, as we * collate in post the file with its image, we get an overlapping * text which is not pixel correct, i.e. which makes the PDF appear * not nicely. * * If the background image is not at least threshold times as large as * the foreground image, we assume we've been working on a * page that was plain text already, and don't add the image * to the background. */ if ((bg_size / fg_size) <= threshold) { log.debug("! Not adding background for page " + i + " since background size (" + bg_size + ") not different enough from foreground size (" + fg_size + ")."); continue; } bg_page = fg_writer.getImportedPage(bg, i); final PdfContentByte contentByte = fg_writer.getUnderContent(i); contentByte.addTemplate(bg_page, 0, 0); } HashMap map = fg_writer.getMoreInfo(); if (map == null) { map = new HashMap(); } if (title != null) { map.put("Title", title); } if (subject != null) { map.put("Subject", subject); } if (keywords != null) { map.put("Keywords", keywords); } if (author != null) { map.put("Author", author); } if (creator != null) { map.put("Creator", creator); } fg_writer.setMoreInfo(map); fg_writer.close(); System.out.println(""); } catch (Exception e) { e.printStackTrace(); } }
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;//www . j a v a 2 s.c o m 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.survey.PdfSurveyServices.java
License:Apache License
/** * *///from w w w . j ava2 s. c om 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 .j a va2s . 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 ww .j a v a2s .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
/** *//*from w ww . j a v a 2 s .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); // 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.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 ww w . jav a 2 s.co 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(); }