List of usage examples for com.lowagie.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
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 www. j a va 2 s.c om*/ * @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
/** * // w w w .j a v a 2 s.co m * This method for Decorating the PDF with watermark. * * @param pdfStamper - 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) { 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); pdfContents = watermarkPdfStamper.getUnderContent(pdfPageNumber); if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { decoratePdfWatermarkImage(pdfContents, (int) rectangle.getHeight(), (int) rectangle.getHeight(), watermarkBean); } if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { decoratePdfWatermarkText(pdfContents, (int) rectangle.getHeight(), (int) rectangle.getHeight(), watermarkBean); } } 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.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.// ww w.j a va2 s . 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 v a 2 s . 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.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); /*//from ww w.j a va2 s . c om * 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 w w. j a v a 2 s. c om*/ 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)); } } } }
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);// w ww . jav a2 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 w w w . j av 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 . jav a 2s.c om*/ 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();/* w w w . ja v a 2 s . com*/ 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(); } }