List of usage examples for com.lowagie.text.pdf PdfStamper PdfStamper
public PdfStamper(PdfReader reader, OutputStream os) throws DocumentException, IOException
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. * //from w w w . j a va 2 s . c o m * @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 w w .j av a 2 s . co m*/ * @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 www.ja v 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/*from www . j ava2s.co 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(); }
From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java
License:Open Source License
/** * This Method creates a custom watermark on the File. * * @param templateStream/*from w ww . ja v a 2 s. c o m*/ * @param watermarkText * @return * @throws IOException * @throws DocumentException */ public static byte[] createWatermarkOnFile(byte[] templateStream, String watermarkText) 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_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gstate = new PdfGState(); gstate.setFillOpacity(0.5f); while (i <= n) { // Watermark under the existing page Rectangle pageSize = pdfReader.getPageSizeWithRotation(i); over = pdfStamper.getOverContent(i); over.beginText(); over.setFontAndSize(bf, 200); over.setGState(gstate); over.setColorFill(Color.LIGHT_GRAY); over.showTextAligned(Element.ALIGN_CENTER, watermarkText, (pageSize.width() / 2), (pageSize.height() / 2), 45); over.endText(); i++; } pdfStamper.close(); } catch (DocumentException ex) { throw new IOException("iText error creating watermark on PDF", ex); } catch (IOException ex) { throw new IOException("IO error creating watermark on PDF", ex); } return outputStream.toByteArray(); }
From source file:org.kuali.kra.printing.service.impl.WatermarkServiceImpl.java
License:Educational Community License
/** * This method for attach watermark with PDF with the help of PdfReader and PdfStamper * //from ww w . j a v a2s .c o m * @param pdfContent pdfContent * @throws DocumentException throws this exception if cannot decorate the pdf * @return byteArrayOutputStream */ private ByteArrayOutputStream attachWatermarking(WatermarkBean watermarkBean, byte pdfContent[]) { PdfReader pdfReader; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfStamper pdfStamp; try { pdfReader = new PdfReader(pdfContent); pdfStamp = new PdfStamper(pdfReader, byteArrayOutputStream); decorateWatermark(pdfStamp, watermarkBean); } catch (IOException decorateWatermark) { LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + decorateWatermark.getMessage()); } catch (DocumentException documentException) { LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + documentException.getMessage()); } return byteArrayOutputStream; }
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./* w w w . jav a 2s. c o 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 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 w w w .j a va 2 s.c om*/ @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.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionAddHeaderFooter(boolean isHeader) throws PageException, IOException, DocumentException { required("pdf", "write", "source", source); // required("pdf", "write", "destination", destination); /*//w w w . j a v a 2s.c o m * optinal - pages */ /* * isBase64 = "yes|no" showonprint = "yes|no"> opacity = "header opacity" image = "image file name to be used as the header" * */ PDFStruct doc = toPDFDocument(source, password, null); PdfReader reader = doc.getPdfReader(); BIF bif = null; if (NUMBERFORMAT_NUMERIC != numberformat) { ClassUtil classUtil = engine.getClassUtil(); try { bif = classUtil.loadBIF(pageContext, "lucee.runtime.functions.displayFormatting.NumberFormat"); } catch (Exception e) { e.printStackTrace(); throw engine.getCastUtil().toPageException(e); } } // output stream boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); OutputStream os = null; if (!Util.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } PdfStamper stamper = null; try { if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); int len = reader.getNumberOfPages(); Set<Integer> pageSet = PDFUtil.parsePageDefinition(pages, len); stamper = new PdfStamper(reader, destination.getOutputStream()); if (font == null) font = getDefaultFont(); // , new Font(FontFamily.HELVETICA, 14) for (int p = 1; p <= len; p++) { if (pageSet != null && !pageSet.contains(p)) continue; Phrase header = text(text, p, len, numberformat, bif, font); // vertical orientation float y; if (isHeader) { y = reader.getPageSize(p).getTop(header.getFont().getCalculatedSize() + (topmargin - 3)); } else { y = reader.getPageSize(p).getBottom((bottommargin + 2)); /* * System.out.println("y:"+y); System.out.println("bottom:"+reader.getPageSize(p).getBottom()); System.out.println("margin:"+bottommargin); * System.out.println("font:"+header.getFont().getSize()); System.out.println("CalculatedStyle:"+header.getFont().getCalculatedStyle()); * System.out.println("CalculatedSize:"+header.getFont().getCalculatedSize()); */ } // float yh = reader.getPageSize(p).getTop(topmargin); // float yf = reader.getPageSize(p).getBottom(bottommargin); System.out.println("++++++++++++"); System.out.println(y); System.out.println(reader.getPageSize(p).getTop()); // horizontal orientation float x = reader.getPageSize(p).getWidth() / 2; if (Element.ALIGN_LEFT == align) { x = leftmargin; } else if (Element.ALIGN_RIGHT == align) { x = reader.getPageSize(p).getWidth() - rightmargin; } else { x = reader.getPageSize(p).getWidth() / 2; } ColumnText.showTextAligned(stamper.getOverContent(p), align, header, x, y, 0); } } finally { try { if (stamper != null) stamper.close(); } catch (IOException ioe) { } ; 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)); } } } // PdfReader pr = doc.getPdfReader(); // output /* * boolean destIsSource = doc.getResource()!=null && destination.equals(doc.getResource()); * * OutputStream os=null; if(destIsSource){ os=new ByteArrayOutputStream(); } else if(destination!=null) { os=destination.getOutputStream(); } * * try { PDFUtil.concat(new PDFStruct[]{doc}, os, true, true, true,version); } finally { Util.closeEL(os); if(os instanceof ByteArrayOutputStream) { * if(destination!=null)engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()), destination,true);// MUST overwrite * } } */ }
From source file:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionAddWatermark() throws PageException, IOException, DocumentException { required("pdf", "addWatermark", "source", source); if (copyFrom == null && image == null) throw engine.getExceptionUtil().createApplicationException( "at least one of the following attributes must be defined " + "[copyFrom,image]"); if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); // image/*from w ww . j a v a 2s. c o m*/ Image img = null; if (image != null) { // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null); // TODO img=Image.getInstance(ri.getBufferedImage(),null,false); } // copy From else { byte[] barr; try { Resource res = copyFrom instanceof String ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom) : engine.getCastUtil().toResource(copyFrom); barr = PDFUtil.toBytes(res); } catch (PageException ee) { barr = engine.getCastUtil().toBinary(copyFrom); } img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false); } // position float x = UNDEFINED, y = UNDEFINED; if (!Util.isEmpty(position)) { int index = position.indexOf(','); if (index == -1) throw engine.getExceptionUtil() .createApplicationException("attribute [position] has an invalid value [" + position + "]," + "value should follow one of the following pattern [40,50], [40,] or [,50]"); String strX = position.substring(0, index).trim(); String strY = position.substring(index + 1).trim(); if (!Util.isEmpty(strX)) x = engine.getCastUtil().toIntValue(strX); if (!Util.isEmpty(strY)) y = engine.getCastUtil().toIntValue(strY); } PDFStruct doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); reader.consolidateNamedDestinations(); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); 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); if (len > 0) { if (x == UNDEFINED || y == UNDEFINED) { PdfImportedPage first = stamp.getImportedPage(reader, 1); if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2; if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2; } img.setAbsolutePosition(x, y); // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte } // rotation if (rotation != 0) { img.setRotationDegrees(rotation); } 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(); // print.out("op:"+opacity); gs1.setFillOpacity(opacity); // gs1.setStrokeOpacity(opacity); 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)); } } } }