List of usage examples for com.lowagie.text.pdf PdfStamper setFormFlattening
public void setFormFlattening(boolean flat)
From source file:org.fenixedu.ulisboa.specifications.ui.firstTimeCandidacy.util.CGDPdfFiller.java
License:Open Source License
private ByteArrayOutputStream getFilledPdfCGDPersonalInformation(Person person, InputStream pdfTemplateStream) throws IOException, DocumentException { PdfReader reader = new PdfReader(pdfTemplateStream); reader.getAcroForm().remove(PdfName.SIGFLAGS); reader.selectPages("1,3,4"); // The template we are using has a blank page after the front sheet. ByteArrayOutputStream output = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(reader, output); form = stamper.getAcroFields();/*ww w .j a v a 2 s .c om*/ setField("T_NomeComp", person.getName()); setField("T_Email", getMail(person)); if (person.isFemale()) { setField("CB_0_1", "Yes"); // female } else { setField("CB_0_0", "Yes"); // male } if (person.getDateOfBirthYearMonthDay() != null) { setField("Cod_data_1", person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("yyyy/MM/dd"))); } setField("NIF1", person.getSocialSecurityNumber()); setField("T_DocIdent", person.getDocumentIdNumber()); switch (person.getMaritalStatus()) { case CIVIL_UNION: setField("CB_EstCivil01", MARITAL_STATUS_CIVIL_UNION); break; case DIVORCED: setField("CB_EstCivil01", MARITAL_STATUS_DIVORCED); break; case MARRIED: setField("CB_EstCivil01", ""); break; case SEPARATED: setField("CB_EstCivil01", MARITAL_STATUS_SEPARATED); break; case SINGLE: setField("CB_EstCivil01", MARITAL_STATUS_SINGLE); break; case WIDOWER: setField("CB_EstCivil01", MARITAL_STATUS_WIDOWER); break; } YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay(); if (emissionDate != null) { setField("Cod_data_2", emissionDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd"))); } YearMonthDay expirationDate = person.getExpirationDateOfDocumentIdYearMonthDay(); if (expirationDate != null) { setField("Cod_data_3", expirationDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd"))); } setField("T_NomePai", person.getNameOfFather()); setField("T_NomeMae", person.getNameOfMother()); if (person.getCountryOfBirth() != null) { setField("T_NatPais", person.getCountryOfBirth().getName()); setField("T_Naturali", person.getDistrictOfBirth()); setField("T_NatConc", person.getDistrictSubdivisionOfBirth()); setField("T_NatFreg", person.getParishOfBirth()); setField("T_PaisRes", person.getCountryOfBirth().getCountryNationality().toString()); } setField("T_Morada01", person.getAddress()); setField("T_Localid01", person.getAreaOfAreaCode()); setField("T_Telef", person.getDefaultMobilePhoneNumber()); String postalCode = person.getPostalCode(); int dashIndex = postalCode.indexOf('-'); if (postalCode != null && postalCode.length() >= dashIndex + 4) { setField("T_CodPos01", postalCode.substring(0, 4)); String last3Numbers = postalCode.substring(dashIndex + 1, dashIndex + 4); setField("T_CodPos03_1", last3Numbers); setField("T_Localid02_1", person.getAreaOfAreaCode()); } if (person.getCountryOfResidence() != null) { setField("T_Distrito", person.getDistrictOfResidence()); setField("T_Conc", person.getDistrictSubdivisionOfResidence()); setField("T_Freguesia", person.getParishOfResidence()); setField("T_PaisResid", person.getCountryOfResidence().getName()); } stamper.setFormFlattening(true); stamper.close(); return output; }
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * This method for applying watermark to the pdf * //from w w w . j av a 2 s.c o m * @return pdfFileData */ public byte[] applyWatermark(byte[] pdfBytes, WatermarkBean watermarkBean) throws Exception { byte[] pdfFileData = pdfBytes; try { if (watermarkBean != null) { // flatten original PDF before adding watermark. This prevents interactive form data from getting lost. PdfReader origFile = new PdfReader(pdfBytes); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(origFile, byteArrayOutputStream); stamper.setFormFlattening(true); stamper.close(); byteArrayOutputStream = attachWatermarking(watermarkBean, byteArrayOutputStream.toByteArray()); pdfFileData = byteArrayOutputStream.toByteArray(); } } catch (Exception exception) { LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception); } return pdfFileData; }
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * //from w w w. ja v a 2 s .c om * This method for Decorating the PDF with watermark. * * @param watermarkPdfStamper - wrapper for pdf content byte and assists in decorating PDF LOg the exception if cannot open/read the file * for decoration */ private void decorateWatermark(PdfStamper watermarkPdfStamper, WatermarkBean watermarkBean) { watermarkPdfStamper.setFormFlattening(true); PdfReader pdfReader = watermarkPdfStamper.getReader(); int pageCount = pdfReader.getNumberOfPages(); int pdfPageNumber = 0; PdfContentByte pdfContents; Rectangle rectangle; while (pdfPageNumber < pageCount) { pdfPageNumber++; pdfContents = watermarkPdfStamper.getOverContent(pdfPageNumber); rectangle = pdfReader.getPageSizeWithRotation(pdfPageNumber); if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { decoratePdfWatermarkImage(pdfContents, (int) rectangle.getWidth(), (int) rectangle.getHeight(), watermarkBean); } if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { decoratePdfWatermarkText(pdfContents, rectangle, watermarkBean); } watermarkPdfStamper.setFormFlattening(true); } try { watermarkPdfStamper.close(); } catch (IOException decorateWatermark) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + decorateWatermark.getMessage()); } catch (DocumentException documentException) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + documentException.getMessage()); } }
From source file:org.kuali.kfs.fp.document.service.impl.CashReceiptCoverSheetServiceImpl.java
License:Open Source License
/** * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field * values on a PDF Form Template./* w ww . j ava 2 s . c om*/ * * @param document The cash receipt document the values will be pulled from. * @param searchPath The directory path of the template to be used to generate the cover sheet. * @param returnStream The output stream the cover sheet will be written to. */ protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception { String templateName = CR_COVERSHEET_TEMPLATE_NM; try { // populate form with document values //KFSMI-7303 //The PDF template is retrieved through web static URL rather than file path, so the File separator is unnecessary final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP"); //skip the File.separator if reference by web resource PdfStamper stamper = new PdfStamper( new PdfReader(searchPath + (isWebResourcePath ? "" : File.separator) + templateName), returnStream); AcroFields populatedCoverSheet = stamper.getAcroFields(); populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber()); populatedCoverSheet.setField(INITIATOR_FIELD, document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()); populatedCoverSheet.setField(CREATED_DATE_FIELD, document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString()); populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString()); populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD, document.getDocumentHeader().getOrganizationDocumentNumber()); populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode()); if (document.getDepositDate() != null) { // This value won't be set until the CR document is // deposited. A CR document is deposited only when it has // been associated with a Cash Management Document (CMD) // and with a Deposit within that CMD. And only when the // CMD is submitted and FINAL, will the CR documents // associated with it, be "deposited." So this value will // fill in at an arbitrarily later point in time. So your // code shouldn't expect it, but if it's there, then // display it. populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString()); } populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription()); populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation()); /* * We should print original amounts before cash manager approves the CR; after that, we should print confirmed amounts. * Note that, in CashReceiptAction.printCoverSheet, it always retrieves the CR from DB, rather than from the current form. * Since during CashManagement route node, the CR can't be saved until CM approves/disapproves the document; this means * that if CM prints during this route node, he will get the original amounts. This is consistent with our logic here. */ boolean isConfirmed = document.isConfirmed(); KualiDecimal totalCheckAmount = !isConfirmed ? document.getTotalCheckAmount() : document.getTotalConfirmedCheckAmount(); KualiDecimal totalCurrencyAmount = !isConfirmed ? document.getTotalCurrencyAmount() : document.getTotalConfirmedCurrencyAmount(); KualiDecimal totalCoinAmount = !isConfirmed ? document.getTotalCoinAmount() : document.getTotalConfirmedCoinAmount(); KualiDecimal totalCashInAmount = !isConfirmed ? document.getTotalCashInAmount() : document.getTotalConfirmedCashInAmount(); KualiDecimal totalMoneyInAmount = !isConfirmed ? document.getTotalMoneyInAmount() : document.getTotalConfirmedMoneyInAmount(); KualiDecimal totalChangeCurrencyAmount = !isConfirmed ? document.getTotalChangeCurrencyAmount() : document.getTotalConfirmedChangeCurrencyAmount(); KualiDecimal totalChangeCoinAmount = !isConfirmed ? document.getTotalChangeCoinAmount() : document.getTotalConfirmedChangeCoinAmount(); KualiDecimal totalChangeAmount = !isConfirmed ? document.getTotalChangeAmount() : document.getTotalConfirmedChangeAmount(); KualiDecimal totalNetAmount = !isConfirmed ? document.getTotalNetAmount() : document.getTotalConfirmedNetAmount(); populatedCoverSheet.setField(CHECKS_FIELD, totalCheckAmount.toString()); populatedCoverSheet.setField(CURRENCY_FIELD, totalCurrencyAmount.toString()); populatedCoverSheet.setField(COIN_FIELD, totalCoinAmount.toString()); populatedCoverSheet.setField(CASH_IN_FIELD, totalCashInAmount.toString()); populatedCoverSheet.setField(MONEY_IN_FIELD, totalMoneyInAmount.toString()); populatedCoverSheet.setField(CHANGE_CURRENCY_FIELD, totalChangeCurrencyAmount.toString()); populatedCoverSheet.setField(CHANGE_COIN_FIELD, totalChangeCoinAmount.toString()); populatedCoverSheet.setField(CHANGE_OUT_FIELD, totalChangeAmount.toString()); populatedCoverSheet.setField(RECONCILIATION_TOTAL_FIELD, totalNetAmount.toString()); stamper.setFormFlattening(true); stamper.close(); } catch (Exception e) { LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e); throw e; } }
From source file:org.kuali.kfs.fp.document.service.impl.DisbursementVoucherCoverSheetServiceImpl.java
License:Open Source License
/** * This method uses the values provided to build and populate a cover sheet associated with a given DisbursementVoucher. * //w w w . ja v a 2 s. com * @param templateDirectory The directory where the cover sheet template can be found. * @param templateName The name of the cover sheet template to be used to build the cover sheet. * @param document The DisbursementVoucher the cover sheet will be populated from. * @param outputStream The stream the cover sheet file will be written to. * @see org.kuali.kfs.fp.document.service.DisbursementVoucherCoverSheetService#generateDisbursementVoucherCoverSheet(java.lang.String, * java.lang.String, org.kuali.kfs.fp.document.DisbursementVoucherDocument, java.io.OutputStream) */ public void generateDisbursementVoucherCoverSheet(String templateDirectory, String templateName, DisbursementVoucherDocument document, OutputStream outputStream) throws DocumentException, IOException { if (this.isCoverSheetPrintable(document)) { String attachment = ""; String handling = ""; String alien = ""; String lines = ""; String bar = ""; String rlines = ""; String docNumber = document.getDocumentNumber(); String initiator = document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId(); String payee = document.getDvPayeeDetail().getDisbVchrPayeePersonName(); String reason = ((PaymentReasonCode) businessObjectService.findBySinglePrimaryKey( PaymentReasonCode.class, document.getDvPayeeDetail().getDisbVchrPaymentReasonCode())).getName(); String check_total = document.getDisbVchrCheckTotalAmount().toString(); String currency = new PaymentMethodValuesFinder().getKeyLabel(document.getDisbVchrPaymentMethodCode()); String address = retrieveAddress(document.getDisbursementVoucherDocumentationLocationCode()); // retrieve attachment label if (document.isDisbVchrAttachmentCode()) { attachment = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_ATTACHMENT_PARM_NM); } // retrieve handling label if (document.isDisbVchrSpecialHandlingCode()) { handling = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_HANDLING_PARM_NM); } // retrieve data for alien payment code if (document.getDvPayeeDetail().isDisbVchrAlienPaymentCode()) { String taxDocumentationLocationCode = parameterService.getParameterValueAsString( DisbursementVoucherDocument.class, DisbursementVoucherConstants.TAX_DOCUMENTATION_LOCATION_CODE_PARM_NM); address = retrieveAddress(taxDocumentationLocationCode); alien = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_ALIEN_PARM_NM); lines = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_LINES_PARM_NM); } // determine if non-employee travel payment reasons String paymentReasonCode = document.getDvPayeeDetail().getDisbVchrPaymentReasonCode(); ParameterEvaluator travelNonEmplPaymentReasonEvaluator = /*REFACTORME*/SpringContext .getBean(ParameterEvaluatorService.class) .getParameterEvaluator(DisbursementVoucherDocument.class, DisbursementVoucherConstants.NONEMPLOYEE_TRAVEL_PAY_REASONS_PARM_NM, paymentReasonCode); boolean isTravelNonEmplPaymentReason = travelNonEmplPaymentReasonEvaluator.evaluationSucceeds(); if (isTravelNonEmplPaymentReason) { bar = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_BAR_PARM_NM); rlines = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_RLINES_PARM_NM); } try { PdfReader reader = new PdfReader(templateDirectory + templateName); // populate form with document values PdfStamper stamper = new PdfStamper(reader, outputStream); AcroFields populatedCoverSheet = stamper.getAcroFields(); populatedCoverSheet.setField("initiator", initiator); populatedCoverSheet.setField("attachment", attachment); populatedCoverSheet.setField("currency", currency); populatedCoverSheet.setField("handling", handling); populatedCoverSheet.setField("alien", alien); populatedCoverSheet.setField("payee_name", payee); populatedCoverSheet.setField("check_total", check_total); populatedCoverSheet.setField("docNumber", docNumber); populatedCoverSheet.setField("payment_reason", reason); populatedCoverSheet.setField("destination_address", address); populatedCoverSheet.setField("lines", lines); populatedCoverSheet.setField("bar", bar); populatedCoverSheet.setField("rlines", rlines); stamper.setFormFlattening(true); stamper.close(); } catch (DocumentException e) { LOG.error("Error creating coversheet for: " + docNumber + ". ::" + e); throw e; } catch (IOException e) { LOG.error("Error creating coversheet for: " + docNumber + ". ::" + e); throw e; } } }
From source file:org.kuali.ole.fp.document.service.impl.CashReceiptCoverSheetServiceImpl.java
License:Educational Community License
/** * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field * values on a PDF Form Template./*from w w w . j av a2 s. c om*/ * * @param document The cash receipt document the values will be pulled from. * @param searchPath The directory path of the template to be used to generate the cover sheet. * @param returnStream The output stream the cover sheet will be written to. */ protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception { String templateName = CR_COVERSHEET_TEMPLATE_NM; try { // populate form with document values //KFSMI-7303 //The PDF template is retrieve through web static URL rather than file path, so the File separator is unnecessary final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP"); //skip the File.separator if reference by web resource PdfStamper stamper = new PdfStamper( new PdfReader(searchPath + (isWebResourcePath ? "" : File.separator) + templateName), returnStream); AcroFields populatedCoverSheet = stamper.getAcroFields(); populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber()); populatedCoverSheet.setField(INITIATOR_FIELD, document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()); populatedCoverSheet.setField(CREATED_DATE_FIELD, document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString()); populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString()); populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD, document.getDocumentHeader().getOrganizationDocumentNumber()); populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode()); if (document.getDepositDate() != null) { // This value won't be set until the CR document is // deposited. A CR document is deposited only when it has // been associated with a Cash Management Document (CMD) // and with a Deposit within that CMD. And only when the // CMD is submitted and FINAL, will the CR documents // associated with it, be "deposited." So this value will // fill in at an arbitrarily later point in time. So your // code shouldn't expect it, but if it's there, then // display it. populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString()); } populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription()); populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation()); populatedCoverSheet.setField(CHECKS_FIELD, document.getTotalCheckAmount().toString()); populatedCoverSheet.setField(CURRENCY_FIELD, document.getTotalCashAmount().toString()); populatedCoverSheet.setField(COIN_FIELD, document.getTotalCoinAmount().toString()); populatedCoverSheet.setField(CHANGE_OUT_FIELD, document.getTotalChangeAmount().toString()); populatedCoverSheet.setField(TOTAL_RECONCILIATION_FIELD, document.getTotalDollarAmount().toString()); stamper.setFormFlattening(true); stamper.close(); } catch (Exception e) { LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e); throw e; } }
From source file:org.kuali.ole.fp.document.service.impl.DisbursementVoucherCoverSheetServiceImpl.java
License:Educational Community License
/** * This method uses the values provided to build and populate a cover sheet associated with a given DisbursementVoucher. * * @param templateDirectory The directory where the cover sheet template can be found. * @param templateName The name of the cover sheet template to be used to build the cover sheet. * @param document The DisbursementVoucher the cover sheet will be populated from. * @param outputStream The stream the cover sheet file will be written to. * @see org.kuali.ole.fp.document.service.DisbursementVoucherCoverSheetService#generateDisbursementVoucherCoverSheet(java.lang.String, * java.lang.String, org.kuali.ole.fp.document.DisbursementVoucherDocument, java.io.OutputStream) *///from ww w . j a v a 2s .c o m @Override public void generateDisbursementVoucherCoverSheet(String templateDirectory, String templateName, DisbursementVoucherDocument document, OutputStream outputStream) throws DocumentException, IOException { if (this.isCoverSheetPrintable(document)) { String attachment = ""; String handling = ""; String alien = ""; String lines = ""; String bar = ""; String rlines = ""; String docNumber = document.getDocumentNumber(); String initiator = document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId(); String payee = document.getDvPayeeDetail().getDisbVchrPayeePersonName(); String reason = businessObjectService.findBySinglePrimaryKey(PaymentReasonCode.class, document.getDvPayeeDetail().getDisbVchrPaymentReasonCode()).getName(); String check_total = document.getDisbVchrCheckTotalAmount().toString(); String currency = new PaymentMethodValuesFinder().getKeyLabel(document.getDisbVchrPaymentMethodCode()); String address = retrieveAddress(document.getDisbursementVoucherDocumentationLocationCode()); // retrieve attachment label if (document.isDisbVchrAttachmentCode()) { attachment = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_ATTACHMENT_PARM_NM); } // retrieve handling label if (document.isDisbVchrSpecialHandlingCode()) { handling = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_HANDLING_PARM_NM); } // retrieve data for alien payment code //Commented for the jira issue OLE-3415 /*if (document.getDvPayeeDetail().isDisbVchrAlienPaymentCode()) { String taxDocumentationLocationCode = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.TAX_DOCUMENTATION_LOCATION_CODE_PARM_NM); address = retrieveAddress(taxDocumentationLocationCode); alien = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_ALIEN_PARM_NM); lines = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_LINES_PARM_NM); }*/ // determine if non-employee travel payment reasons String paymentReasonCode = document.getDvPayeeDetail().getDisbVchrPaymentReasonCode(); //Commented for the jira issue OLE-3415 /*ParameterEvaluator travelNonEmplPaymentReasonEvaluator = SpringContext.getBean(ParameterEvaluatorService.class).getParameterEvaluator(DisbursementVoucherDocument.class, DisbursementVoucherConstants.NONEMPLOYEE_TRAVEL_PAY_REASONS_PARM_NM, paymentReasonCode); boolean isTravelNonEmplPaymentReason = travelNonEmplPaymentReasonEvaluator.evaluationSucceeds(); if (isTravelNonEmplPaymentReason) { bar = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_BAR_PARM_NM); rlines = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_RLINES_PARM_NM); }*/ try { PdfReader reader = new PdfReader(templateDirectory + templateName); // populate form with document values PdfStamper stamper = new PdfStamper(reader, outputStream); AcroFields populatedCoverSheet = stamper.getAcroFields(); populatedCoverSheet.setField("initiator", initiator); populatedCoverSheet.setField("attachment", attachment); populatedCoverSheet.setField("currency", currency); populatedCoverSheet.setField("handling", handling); populatedCoverSheet.setField("alien", alien); populatedCoverSheet.setField("payee_name", payee); populatedCoverSheet.setField("check_total", check_total); populatedCoverSheet.setField("docNumber", docNumber); populatedCoverSheet.setField("payment_reason", reason); populatedCoverSheet.setField("destination_address", address); populatedCoverSheet.setField("lines", lines); populatedCoverSheet.setField("bar", bar); populatedCoverSheet.setField("rlines", rlines); stamper.setFormFlattening(true); stamper.close(); } catch (DocumentException e) { LOG.error("Error creating coversheet for: " + docNumber + ". ::" + e); throw e; } catch (IOException e) { LOG.error("Error creating coversheet for: " + docNumber + ". ::" + e); throw e; } } }
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;/* w w w. j a v a2 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 www .ja v a 2 s.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?) /*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
/** * *//* ww w.j a v a2s . co m*/ public static Map<String, Object> buildSurveyResponseFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) { String surveyResponseId = null; Locale locale = (Locale) context.get("locale"); try { Delegator delegator = dctx.getDelegator(); String partyId = (String) context.get("partyId"); String surveyId = (String) context.get("surveyId"); //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; }