List of usage examples for com.lowagie.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void stampImage(int pageCount, PdfPageData currentPageData, final StampImageToPDFPages stampImage) { File tempFile = null;// w ww . ja v a2 s .c o m try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = stampImage.getPages(); if (pgsToEdit == null) return; File fileToTest = new File(stampImage.getImageLocation()); if (!fileToTest.exists()) { currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.ImageDoesNotExist")); return; } List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); int n = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); Image img = Image.getInstance(fileToTest.getAbsolutePath()); int chosenWidthScale = stampImage.getWidthScale(); int chosenHeightScale = stampImage.getHeightScale(); img.scalePercent(chosenWidthScale, chosenHeightScale); String chosenPlacement = stampImage.getPlacement(); int chosenRotation = stampImage.getRotation(); img.setRotationDegrees(chosenRotation); String chosenHorizontalPosition = stampImage.getHorizontalPosition(); String chosenVerticalPosition = stampImage.getVerticalPosition(); float chosenHorizontalOffset = stampImage.getHorizontalOffset(); float chosenVerticalOffset = stampImage.getVerticalOffset(); for (int page = 0; page <= n; page++) { if (pagesToEdit.contains(new Integer(page))) { PdfContentByte cb; if (chosenPlacement.equals("Overlay")) cb = stamp.getOverContent(page); else cb = stamp.getUnderContent(page); int currentRotation = currentPageData.getRotation(page); Rectangle pageSize; if (currentRotation == 90 || currentRotation == 270) pageSize = reader.getPageSize(page).rotate(); else pageSize = reader.getPageSize(page); float startx, starty; if (chosenVerticalPosition.equals("From the top")) { starty = pageSize.height() - ((img.height() * (chosenHeightScale / 100)) / 2); } else if (chosenVerticalPosition.equals("Centered")) { starty = (pageSize.height() / 2) - ((img.height() * (chosenHeightScale / 100)) / 2); } else { starty = 0; } if (chosenHorizontalPosition.equals("From the left")) { startx = 0; } else if (chosenHorizontalPosition.equals("Centered")) { startx = (pageSize.width() / 2) - ((img.width() * (chosenWidthScale / 100)) / 2); } else { startx = pageSize.width() - ((img.width() * (chosenWidthScale / 100)) / 2); } img.setAbsolutePosition(startx + chosenHorizontalOffset, starty + chosenVerticalOffset); cb.addImage(img); } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void stampText(int pageCount, PdfPageData currentPageData, final StampTextToPDFPages stampText) { File tempFile = null;/* ww w .ja va2 s . com*/ try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = stampText.getPages(); if (pgsToEdit == null) return; List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); for (int page = 1; page <= pageCount; page++) { if (pagesToEdit.contains(new Integer(page))) { String chosenText = stampText.getText(); if (!chosenText.equals("")) { String chosenFont = stampText.getFontName(); Color chosenFontColor = stampText.getFontColor(); int chosenFontSize = stampText.getFontSize(); int chosenRotation = stampText.getRotation(); String chosenPlacement = stampText.getPlacement(); String chosenHorizontalPosition = stampText.getHorizontalPosition(); String chosenVerticalPosition = stampText.getVerticalPosition(); float chosenHorizontalOffset = stampText.getHorizontalOffset(); float chosenVerticalOffset = stampText.getVerticalOffset(); BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false); PdfContentByte cb; if (chosenPlacement.equals("Overlay")) cb = stamp.getOverContent(page); else cb = stamp.getUnderContent(page); cb.beginText(); cb.setColorFill(chosenFontColor); cb.setFontAndSize(font, chosenFontSize); int currentRotation = currentPageData.getRotation(page); Rectangle pageSize; if (currentRotation == 90 || currentRotation == 270) pageSize = reader.getPageSize(page).rotate(); else pageSize = reader.getPageSize(page); float startx; float starty; if (chosenVerticalPosition.equals("From the top")) { starty = pageSize.height(); } else if (chosenVerticalPosition.equals("Centered")) { starty = pageSize.height() / 2; } else { starty = 0; } if (chosenHorizontalPosition.equals("From the left")) { startx = 0; } else if (chosenHorizontalPosition.equals("Centered")) { startx = pageSize.width() / 2; } else { startx = pageSize.width(); } cb.showTextAligned(Element.ALIGN_CENTER, chosenText, startx + chosenHorizontalOffset, starty + chosenVerticalOffset, chosenRotation); cb.endText(); } } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void addHeaderFooter(int pageCount, PdfPageData currentPageData, final AddHeaderFooterToPDFPages addHeaderFooter) { File tempFile = null;//from w w w .ja va2 s .co m try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = addHeaderFooter.getPages(); if (pgsToEdit == null) return; List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); String chosenFont = addHeaderFooter.getFontName(); Color chosenFontColor = addHeaderFooter.getFontColor(); int chosenFontSize = addHeaderFooter.getFontSize(); float chosenLeftRightMargin = addHeaderFooter.getLeftRightMargin(); float chosenTopBottomMargin = addHeaderFooter.getTopBottomMargin(); String text[] = new String[6]; text[0] = addHeaderFooter.getLeftHeader(); text[1] = addHeaderFooter.getCenterHeader(); text[2] = addHeaderFooter.getRightHeader(); text[3] = addHeaderFooter.getLeftFooter(); text[4] = addHeaderFooter.getCenterFooter(); text[5] = addHeaderFooter.getRightFooter(); Date date = new Date(); String shortDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date); String longDate = DateFormat.getDateInstance(DateFormat.LONG).format(date); SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a"); String time12 = formatter.format(date); formatter = new SimpleDateFormat("HH.mm.ss"); String time24 = formatter.format(date); String fileName = new File(selectedFile).getName(); BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false); for (int page = 1; page <= pageCount; page++) { if (pagesToEdit.contains(new Integer(page))) { String[] textCopy = new String[text.length]; System.arraycopy(text, 0, textCopy, 0, text.length); for (int i = 0; i < 6; i++) { textCopy[i] = textCopy[i].replaceAll("<d>", shortDate); textCopy[i] = textCopy[i].replaceAll("<D>", longDate); textCopy[i] = textCopy[i].replaceAll("<t>", time12); textCopy[i] = textCopy[i].replaceAll("<T>", time24); textCopy[i] = textCopy[i].replaceAll("<f>", fileName); textCopy[i] = textCopy[i].replaceAll("<F>", selectedFile); textCopy[i] = textCopy[i].replaceAll("<p>", "" + page); textCopy[i] = textCopy[i].replaceAll("<P>", "" + pageCount); } PdfContentByte cb = stamp.getOverContent(page); cb.beginText(); cb.setColorFill(chosenFontColor); cb.setFontAndSize(font, chosenFontSize); Rectangle pageSize = reader.getPageSizeWithRotation(page); cb.showTextAligned(Element.ALIGN_LEFT, textCopy[0], chosenLeftRightMargin, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_CENTER, textCopy[1], pageSize.width() / 2, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[2], pageSize.width() - chosenLeftRightMargin, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_LEFT, textCopy[3], chosenLeftRightMargin, chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_CENTER, textCopy[4], pageSize.width() / 2, chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[5], pageSize.width() - chosenLeftRightMargin, chosenTopBottomMargin, 0); cb.endText(); } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * This method for applying watermark to the pdf * /* ww 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 va2 s .c o m*/ * 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 w w . j a va 2 s .co m * * @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. * /* www .j av a 2 s . c om*/ * @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.kfs.module.ar.report.service.impl.ContractsGrantsInvoiceReportServiceImpl.java
License:Open Source License
/** * * @param template the path to the original form * @param list the replacement list// w ww . j ava 2 s. c om * @return * @throws IOException * @throws DocumentException */ protected byte[] renameFieldsIn(String template, Map<String, String> list) throws IOException, DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Create the stamper PdfStamper stamper = new PdfStamper(new PdfReader(template), baos); // Get the fields AcroFields fields = stamper.getAcroFields(); // Loop over the fields for (String field : list.keySet()) { fields.setField(field, list.get(field)); } // close the stamper stamper.close(); return baos.toByteArray(); }
From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java
License:Open Source License
/** * This Method stamps the values from the map onto the fields in the template provided. * * @param templateStream/*from w ww . j av a 2 s .c om*/ * @param outputStream * @param replacementList * @throws IOException */ private static void pdfStampValues(InputStream templateStream, OutputStream outputStream, Map<String, String> replacementList) throws IOException { try { // Create a PDF reader for the template PdfReader pdfReader = new PdfReader(templateStream); // Create a PDF writer PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream); // Replace the form data with the final values AcroFields fields = pdfStamper.getAcroFields(); for (Object fieldName : fields.getFields().keySet()) { // Read the field data String text = fields.getField(fieldName.toString()); String newText = fields.getField(fieldName.toString()); // Replace the keywords if (fields.getFieldType(fieldName.toString()) == AcroFields.FIELD_TYPE_TEXT) { newText = replaceValuesIteratingThroughFile(text, replacementList); } else { if (ObjectUtils.isNotNull(replacementList.get(fieldName.toString()))) { newText = replacementList.get(fieldName); } } // Populate the field with the final value fields.setField(fieldName.toString(), newText); } // -------------------------------------------------- // Save the new PDF // -------------------------------------------------- pdfStamper.close(); } catch (IOException e) { throw new IOException("IO error processing PDF template", e); } catch (DocumentException e) { throw new IOException("iText error processing PDF template", e); } finally { // -------------------------------------------------- // Close the files // -------------------------------------------------- templateStream.close(); outputStream.close(); } }
From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java
License:Open Source License
/** * This method creates a Final watermark on the input Stream. * * @param templateStream// www . ja v a2 s . c o m * @param finalmarkText * @return * @throws IOException * @throws DocumentException */ public static byte[] createFinalmarkOnFile(byte[] templateStream, String finalmarkText) throws IOException, DocumentException { // Create a PDF reader for the template PdfReader pdfReader = new PdfReader(templateStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Create a PDF writer PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream); int n = pdfReader.getNumberOfPages(); int i = 1; PdfContentByte over; BaseFont bf; try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gstate = new PdfGState(); while (i <= n) { // Watermark under the existing page Rectangle pageSize = pdfReader.getPageSizeWithRotation(i); over = pdfStamper.getOverContent(i); over.beginText(); over.setFontAndSize(bf, 8); over.setGState(gstate); over.setColorFill(Color.BLACK); over.showTextAligned(Element.ALIGN_CENTER, finalmarkText, (pageSize.width() / 2), (pageSize.height() - 10), 0); over.endText(); i++; } pdfStamper.close(); } catch (DocumentException ex) { throw new IOException("iText error creating final watermark on PDF", ex); } catch (IOException ex) { throw new IOException("IO error creating final watermark on PDF", ex); } return outputStream.toByteArray(); }