List of usage examples for com.lowagie.text Image getInstance
public static Image getInstance(Image image)
From source file:org.inbio.modeling.core.manager.impl.ExportManagerImpl.java
License:Open Source License
private void addImageSection(Document d, String mapName, Long currentSessionId) throws BadElementException, MalformedURLException, IOException, DocumentException { Image mapImage = Image.getInstance(mapsHome + mapName + "_T_" + currentSessionId + ".png"); mapImage.scaleToFit(550, 413);/*from w w w . j a v a 2 s . com*/ mapImage.setAlignment(Image.ALIGN_LEFT); // scale Image scaleImage = Image.getInstance(mapsHome + "scale.jpg"); scaleImage.scaleToFit(30, 150); scaleImage.setAlignment(Image.ALIGN_RIGHT); Paragraph images = new Paragraph(); images.setAlignment(Paragraph.ALIGN_RIGHT); //upper scale leyend images.add(new Chunk(this.getI18nString("pdfReport.scaleUpper") + "\n\n\n\n\n\n\n", new Font(Font.COURIER, 8, Font.BOLDITALIC))); // Map images.add(new Chunk(mapImage, 1F, 1F)); // Scale images.add(new Chunk(scaleImage, 1F, 1F)); // lower scale leyend images.add(new Chunk("\n" + this.getI18nString("pdfReport.scaleLower") + "\n", new Font(Font.COURIER, 8, Font.BOLDITALIC))); d.add(images); }
From source file:org.jbpm.designer.web.server.TransformerServlet.java
License:Apache License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String formattedSvgEncoded = req.getParameter("fsvg"); String uuid = Utils.getUUID(req); String profileName = Utils.getDefaultProfileName(req.getParameter("profile")); String transformto = req.getParameter("transformto"); String jpdl = req.getParameter("jpdl"); String gpd = req.getParameter("gpd"); String bpmn2in = req.getParameter("bpmn2"); String jsonin = req.getParameter("json"); String preprocessingData = req.getParameter("pp"); String respaction = req.getParameter("respaction"); String pp = req.getParameter("pp"); String processid = req.getParameter("processid"); String sourceEnc = req.getParameter("enc"); String convertServiceTasks = req.getParameter("convertservicetasks"); String htmlSourceEnc = req.getParameter("htmlenc"); String formattedSvg = (formattedSvgEncoded == null ? "" : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8")); String htmlSource = (htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8")); if (sourceEnc != null && sourceEnc.equals("true")) { bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8"); }/* w w w . j a va 2 s . co m*/ if (profile == null) { profile = _profileService.findProfile(req, profileName); } DroolsFactoryImpl.init(); BpsimFactoryImpl.init(); Repository repository = profile.getRepository(); if (transformto != null && transformto.equals(TO_PDF)) { if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) { try { ByteArrayOutputStream pdfBout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH); float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT); String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\""; t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint); t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint); ByteArrayOutputStream imageBout = new ByteArrayOutputStream(); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(imageBout); t.transcode(input, output); Image processImage = Image.getInstance(imageBout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getWriter() .write("<object type=\"application/pdf\" " + objStyle + " data=\"data:application/pdf;base64," + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>"); } catch (Exception e) { resp.sendError(500, e.getMessage()); } } else { storeInRepository(uuid, formattedSvg, transformto, processid, repository); try { resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream()); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); Image processImage = Image.getInstance(bout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); } catch (Exception e) { resp.sendError(500, e.getMessage()); } } } else if (transformto != null && transformto.equals(TO_PNG)) { try { if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); if (req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) { int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH); int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT); resp.getWriter() .write("<img width=\"" + widthHint + "\" height=\"" + heightHint + "\" src=\"data:image/png;base64," + Base64.encodeBase64String(bout.toByteArray()) + "\">"); } else { resp.getWriter().write("<img src=\"data:image/png;base64," + Base64.encodeBase64String(bout.toByteArray()) + "\">"); } } else { storeInRepository(uuid, formattedSvg, transformto, processid, repository); resp.setContentType("image/png"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\""); } PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(resp.getOutputStream()); t.transcode(input, output); } } catch (TranscoderException e) { resp.sendError(500, e.getMessage()); } } else if (transformto != null && transformto.equals(TO_SVG)) { storeInRepository(uuid, formattedSvg, transformto, processid, repository); } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) { try { if (convertServiceTasks != null && convertServiceTasks.equals("true")) { bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\""); bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\""); } Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in); def.setTargetNamespace("http://www.omg.org/bpmn20"); if (convertServiceTasks != null && convertServiceTasks.equals("true")) { // fix the data input associations for converted tasks List<RootElement> rootElements = def.getRootElements(); for (RootElement root : rootElements) { if (root instanceof Process) { updateTaskDataInputs((Process) root, def); } } } // get the xml from Definitions ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet .createResource(URI.createURI("virtual.bpmn2")); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, true); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF, JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD); bpmn2resource.setEncoding("UTF-8"); rSet.getResources().add(bpmn2resource); bpmn2resource.getContents().add(def); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bpmn2resource.save(outputStream, new HashMap<Object, Object>()); String revisedXmlModel = outputStream.toString(); String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); resp.getWriter().print(json); } catch (Exception e) { e.printStackTrace(); _logger.error(e.getMessage()); resp.setContentType("application/json"); resp.getWriter().print("{}"); } } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) { try { DroolsFactoryImpl.init(); BpsimFactoryImpl.init(); if (preprocessingData == null) { preprocessingData = ""; } String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData); resp.setContentType("application/xml"); resp.getWriter().print(processXML); } catch (Exception e) { e.printStackTrace(); _logger.error(e.getMessage()); resp.setContentType("application/xml"); resp.getWriter().print(""); } } else if (transformto != null && transformto.equals(HTML_TO_PDF)) { try { resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream()); pdfDoc.open(); pdfDoc.addCreator("jBPM Designer"); pdfDoc.addSubject("Business Process Documentation"); pdfDoc.addCreationDate(); pdfDoc.addTitle("Process Documentation"); HTMLWorker htmlWorker = new HTMLWorker(pdfDoc); htmlWorker.parse(new StringReader(htmlSource)); pdfDoc.close(); } catch (DocumentException e) { resp.sendError(500, e.getMessage()); } } }
From source file:org.jbpm.designer.web.server.TransformerServlet.java
License:Apache License
protected void storeInRepository(String uuid, String svg, String transformto, String processid, Repository repository) {/* www .ja v a 2 s .com*/ String assetFullName = ""; try { if (processid != null) { Asset<byte[]> processAsset = repository.loadAsset(uuid); String assetExt = ""; String assetFileExt = ""; if (transformto.equals(TO_PDF)) { assetExt = "-pdf"; assetFileExt = ".pdf"; } if (transformto.equals(TO_PNG)) { assetExt = "-image"; assetFileExt = ".png"; } if (transformto.equals(TO_SVG)) { assetExt = "-svg"; assetFileExt = ".svg"; } if (processid.startsWith(".")) { processid = processid.substring(1, processid.length()); } assetFullName = processid + assetExt + assetFileExt; repository.deleteAssetFromPath( processAsset.getAssetLocation().replaceAll("\\s", "%20") + "/" + assetFullName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (transformto.equals(TO_PDF)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, outputStream); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(svg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); Image processImage = Image.getInstance(bout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); } else if (transformto.equals(TO_PNG)) { PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(svg)); TranscoderOutput output = new TranscoderOutput(outputStream); try { t.transcode(input, output); } catch (Exception e) { // issue with batik here..do not make a big deal _logger.debug(e.getMessage()); } } else if (transformto.equals(TO_SVG)) { OutputStreamWriter outStreamWriter = new OutputStreamWriter(outputStream); outStreamWriter.write(svg); outStreamWriter.close(); } AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte); builder.name(processid + assetExt).type(assetFileExt.substring(1)) .location(processAsset.getAssetLocation().replaceAll("\\s", "%20")) .version(processAsset.getVersion()).content(outputStream.toByteArray()); Asset<byte[]> resourceAsset = builder.getAsset(); repository.createAsset(resourceAsset); } } catch (Exception e) { // just log that error happened if (e.getMessage() != null) { _logger.error(e.getMessage()); } else { _logger.error(e.getClass().toString() + " " + assetFullName); } e.printStackTrace(); } }
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;//from ww w .ja v a 2 s.c om 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.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * This method is for setting the properties of watermark Image. * /*from w w w. java 2 s . c o m*/ * @param pdfContentByte * @param pageWidth * @param pageHeight * @param watermarkBean */ private void decoratePdfWatermarkImage(PdfContentByte pdfContentByte, int pageWidth, int pageHeight, WatermarkBean watermarkBean) { PdfGState pdfGState = new PdfGState(); final float OPACITY = 0.3f; float absPosX; float absPosY; try { if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { Image watermarkImage = Image.getInstance(watermarkBean.getFileImage()); if (watermarkImage != null) { pdfGState.setFillOpacity(OPACITY); pdfContentByte.setGState(pdfGState); float height = watermarkImage.getPlainHeight(); float width = watermarkImage.getPlainWidth(); int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight)); int pivotPoint = (diagonal - (int) width) / 2; float angle = (float) Math.atan((float) pageHeight / pageWidth); absPosX = (float) (pivotPoint * pageWidth) / diagonal; absPosY = (float) (pivotPoint * pageHeight) / diagonal; watermarkImage.setAbsolutePosition(absPosX, absPosY); if ((pageWidth / 2) < width) { watermarkImage.scaleToFit(pageWidth / 2, pageHeight / 2); } else { watermarkImage.scaleToFit(width, height); } pdfContentByte.addImage(watermarkImage); } } } catch (BadElementException badElementException) { LOG.error("WatermarkDecoratorImpl Error found: " + badElementException.getMessage()); } catch (DocumentException documentException) { LOG.error("WatermarkDecoratorImpl Error found: " + documentException.getMessage()); } }
From source file:org.kuali.kfs.module.purap.pdf.BulkReceivingPdf.java
License:Open Source License
private void loadHeaderTable() throws Exception { float[] headerWidths = { 0.20f, 0.80f }; headerTable = new PdfPTable(headerWidths); headerTable.setWidthPercentage(100); headerTable.setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.setSplitLate(false);//from ww w .j av a 2 s. com headerTable.getDefaultCell().setBorderWidth(0); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER); /** * Logo display */ if (StringUtils.isNotBlank(logoImage)) { logo = Image.getInstance(logoImage); logo.scalePercent(3, 3); headerTable.addCell(new Phrase(new Chunk(logo, 0, 0))); } else { headerTable.addCell(new Phrase(new Chunk(""))); } /** * Nested table in tableHeader to display title and doc number */ float[] nestedHeaderWidths = { 0.70f, 0.30f }; nestedHeaderTable = new PdfPTable(nestedHeaderWidths); nestedHeaderTable.setSplitLate(false); PdfPCell cell; /** * Title */ cell = new PdfPCell(new Paragraph("RECEIVING TICKET", ver_15_normal)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); /** * Doc Number */ Paragraph p = new Paragraph(); p.add(new Chunk("Doc Number: ", ver_11_normal)); p.add(new Chunk(blkRecDoc.getDocumentNumber().toString(), cour_10_normal)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); // Add the nestedHeaderTable to the headerTable cell = new PdfPCell(nestedHeaderTable); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); headerTable.addCell(cell); }
From source file:org.kuali.kfs.module.purap.pdf.PurchaseOrderPdf.java
License:Open Source License
/** * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable and set its logo image if * there is a logoImage to be used, creates and sets the nestedHeaderTable and its content. * * @param writer The PdfWriter for this document. * @param document The document./*from w ww. j ava2 s . c o m*/ * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ @Override public void onOpenDocument(PdfWriter writer, Document document) { if (LOG.isDebugEnabled()) { LOG.debug("onOpenDocument() started. isRetransmit is " + isRetransmit); } try { float[] headerWidths = { 0.20f, 0.80f }; headerTable = new PdfPTable(headerWidths); headerTable.setWidthPercentage(100); headerTable.setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.setSplitLate(false); headerTable.getDefaultCell().setBorderWidth(0); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER); Image logo = null; if (StringUtils.isNotBlank(logoImage)) { try { logo = Image.getInstance(logoImage); } catch (IOException e) { LOG.info("The logo image [" + logoImage + "] is not available. Defaulting to the default image."); } } if (logo == null) { // if we don't use images headerTable.addCell(new Phrase(new Chunk(""))); } else { logo.scalePercent(3, 3); headerTable.addCell(new Phrase(new Chunk(logo, 0, 0))); } // Nested table for titles, etc. float[] nestedHeaderWidths = { 0.70f, 0.30f }; nestedHeaderTable = new PdfPTable(nestedHeaderWidths); nestedHeaderTable.setSplitLate(false); PdfPCell cell; // New nestedHeaderTable row cell = new PdfPCell(new Paragraph(po.getBillingName(), ver_15_normal)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); cell = new PdfPCell(new Paragraph(" ", ver_15_normal)); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); // New nestedHeaderTable row if (isRetransmit) { cell = new PdfPCell(new Paragraph(po.getRetransmitHeader(), ver_15_normal)); } else { cell = new PdfPCell(new Paragraph("PURCHASE ORDER", ver_15_normal)); } cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); Paragraph p = new Paragraph(); p.add(new Chunk("PO Number: ", ver_11_normal)); p.add(new Chunk(po.getPurapDocumentIdentifier().toString(), cour_16_bold)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); if (!po.getPurchaseOrderAutomaticIndicator()) { // Contract manager name goes on non-APOs. // New nestedHeaderTable row, spans both columns p = new Paragraph(); p.add(new Chunk("Contract Manager: ", ver_11_normal)); p.add(new Chunk(po.getContractManager().getContractManagerName(), cour_7_normal)); cell = new PdfPCell(p); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBorderWidth(0); nestedHeaderTable.addCell(cell); } // Add the nestedHeaderTable to the headerTable cell = new PdfPCell(nestedHeaderTable); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); headerTable.addCell(cell); // initialization of the template tpl = writer.getDirectContent().createTemplate(100, 100); // initialization of the font helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:org.kuali.kfs.module.purap.pdf.PurchaseOrderPdf.java
License:Open Source License
/** * Create a PDF using the given input parameters. * * @param po The PurchaseOrderDocument to be used to create the pdf. * @param document The pdf document whose margins have already been set. * @param writer The PdfWriter to write the pdf document into. * @param statusInquiryUrl The status inquiry url to be displayed on the pdf document. * @param campusName The campus name to be displayed on the pdf document. * @param contractLanguage The contract language to be displayed on the pdf document. * @param logoImage The logo image file name to be displayed on the pdf document. * @param directorSignatureImage The director signature image to be displayed on the pdf document. * @param directorName The director name to be displayed on the pdf document. * @param directorTitle The director title to be displayed on the pdf document. * @param contractManagerSignatureImage The contract manager signature image to be displayed on the pdf document. * @param isRetransmit The boolean to indicate whether this is for a retransmit purchase order document. * @param environment The current environment used (e.g. DEV if it is a development environment). * @param retransmitItems The items selected by the user to be retransmitted. * @throws DocumentException/* ww w. j a va 2 s . co m*/ * @throws IOException */ private void createPdf(PurchaseOrderDocument po, Document document, PdfWriter writer, String statusInquiryUrl, String campusName, String contractLanguage, String logoImage, String directorSignatureImage, String directorName, String directorTitle, String contractManagerSignatureImage, boolean isRetransmit, String environment, List<PurchaseOrderItem> retransmitItems) throws DocumentException, IOException { if (LOG.isDebugEnabled()) { LOG.debug("createPdf() started for po number " + po.getPurapDocumentIdentifier().toString()); } // These have to be set because they are used by the onOpenDocument() and onStartPage() methods. this.campusName = campusName; this.po = po; this.logoImage = logoImage; this.environment = environment; NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US); Collection errors = new ArrayList(); // Date format pattern: MM-dd-yyyy SimpleDateFormat sdf = PurApDateFormatUtils .getSimpleDateFormat(PurapConstants.NamedDateFormats.KUALI_SIMPLE_DATE_FORMAT_2); // This turns on the page events that handle the header and page numbers. PurchaseOrderPdf events = new PurchaseOrderPdf().getPageEvents(); writer.setPageEvent(this); // Passing in "this" lets it know about the po, campusName, etc. document.open(); PdfPCell cell; Paragraph p = new Paragraph(); // ***** Info table (vendor, address info) ***** LOG.debug("createPdf() info table started."); float[] infoWidths = { 0.50f, 0.50f }; PdfPTable infoTable = new PdfPTable(infoWidths); infoTable.setWidthPercentage(100); infoTable.setHorizontalAlignment(Element.ALIGN_CENTER); infoTable.setSplitLate(false); StringBuffer vendorInfo = new StringBuffer(); vendorInfo.append("\n"); if (StringUtils.isNotBlank(po.getVendorName())) { vendorInfo.append(" " + po.getVendorName() + "\n"); } vendorInfo.append(" ATTN: " + po.getVendorAttentionName() + "\n"); if (StringUtils.isNotBlank(po.getVendorLine1Address())) { vendorInfo.append(" " + po.getVendorLine1Address() + "\n"); } if (StringUtils.isNotBlank(po.getVendorLine2Address())) { vendorInfo.append(" " + po.getVendorLine2Address() + "\n"); } if (StringUtils.isNotBlank(po.getVendorCityName())) { vendorInfo.append(" " + po.getVendorCityName()); } if (StringUtils.isNotBlank(po.getVendorStateCode())) { vendorInfo.append(", " + po.getVendorStateCode()); } if (StringUtils.isNotBlank(po.getVendorAddressInternationalProvinceName())) { vendorInfo.append(", " + po.getVendorAddressInternationalProvinceName()); } if (StringUtils.isNotBlank(po.getVendorPostalCode())) { vendorInfo.append(" " + po.getVendorPostalCode() + "\n"); } else { vendorInfo.append("\n"); } if (!KFSConstants.COUNTRY_CODE_UNITED_STATES.equalsIgnoreCase(po.getVendorCountryCode()) && po.getVendorCountry() != null) { vendorInfo.append(" " + po.getVendorCountry().getName() + "\n\n"); } else { vendorInfo.append("\n\n"); } p = new Paragraph(); p.add(new Chunk(" Vendor", ver_5_normal)); p.add(new Chunk(vendorInfo.toString(), cour_7_normal)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); infoTable.addCell(cell); StringBuffer shipToInfo = new StringBuffer(); shipToInfo.append("\n"); if (po.getAddressToVendorIndicator()) { // use receiving address shipToInfo.append(" " + po.getReceivingName() + "\n"); shipToInfo.append(" " + po.getReceivingLine1Address() + "\n"); if (StringUtils.isNotBlank(po.getReceivingLine2Address())) { shipToInfo.append(" " + po.getReceivingLine2Address() + "\n"); } shipToInfo.append(" " + po.getReceivingCityName() + ", " + po.getReceivingStateCode() + " " + po.getReceivingPostalCode() + "\n"); if (StringUtils.isNotBlank(po.getReceivingCountryCode()) && !KFSConstants.COUNTRY_CODE_UNITED_STATES.equalsIgnoreCase(po.getReceivingCountryCode())) { shipToInfo.append(" " + po.getReceivingCountryName() + "\n"); } } else { // use delivery address shipToInfo.append(" " + po.getDeliveryToName() + "\n"); // extra space needed below to separate other text going on same PDF line String deliveryBuildingName = po.getDeliveryBuildingName() + " "; if (po.isDeliveryBuildingOtherIndicator()) { deliveryBuildingName = ""; } shipToInfo .append(" " + deliveryBuildingName + "Room #" + po.getDeliveryBuildingRoomNumber() + "\n"); shipToInfo.append(" " + po.getDeliveryBuildingLine1Address() + "\n"); if (StringUtils.isNotBlank(po.getDeliveryBuildingLine2Address())) { shipToInfo.append(" " + po.getDeliveryBuildingLine2Address() + "\n"); } shipToInfo.append(" " + po.getDeliveryCityName() + ", " + po.getDeliveryStateCode() + " " + po.getDeliveryPostalCode() + "\n"); if (StringUtils.isNotBlank(po.getDeliveryCountryCode()) && !KFSConstants.COUNTRY_CODE_UNITED_STATES.equalsIgnoreCase(po.getDeliveryCountryCode())) { shipToInfo.append(" " + po.getDeliveryCountryName() + "\n"); } } // display deliveryToPhoneNumber disregard of whether receiving or delivery address is used shipToInfo.append(" " + po.getDeliveryToPhoneNumber()); /* // display deliveryToPhoneNumber based on the parameter indicator, disregard of whether receiving or delivery address is used boolean displayDeliveryPhoneNumber = SpringContext.getBean(ParameterService.class).getIndicatorParameter(PurchaseOrderDocument.class, PurapParameterConstants.DISPLAY_DELIVERY_PHONE_NUMBER_ON_PDF_IND); if (displayDeliveryPhoneNumber && StringUtils.isNotBlank(po.getDeliveryToPhoneNumber())) { shipToInfo.append(" " + po.getDeliveryToPhoneNumber()); } */ p = new Paragraph(); p.add(new Chunk(" Shipping Address", ver_5_normal)); p.add(new Chunk(shipToInfo.toString(), cour_7_normal)); cell = new PdfPCell(p); infoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" Shipping Terms\n", ver_5_normal)); if (po.getVendorShippingPaymentTerms() != null && po.getVendorShippingTitle() != null) { p.add(new Chunk(" " + po.getVendorShippingPaymentTerms().getVendorShippingPaymentTermsDescription(), cour_7_normal)); p.add(new Chunk(" - " + po.getVendorShippingTitle().getVendorShippingTitleDescription(), cour_7_normal)); } else if (po.getVendorShippingPaymentTerms() != null && po.getVendorShippingTitle() == null) { p.add(new Chunk(" " + po.getVendorShippingPaymentTerms().getVendorShippingPaymentTermsDescription(), cour_7_normal)); } else if (po.getVendorShippingTitle() != null && po.getVendorShippingPaymentTerms() == null) { p.add(new Chunk(" " + po.getVendorShippingTitle().getVendorShippingTitleDescription(), cour_7_normal)); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); infoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" Payment Terms\n", ver_5_normal)); if (po.getVendorPaymentTerms() != null) { p.add(new Chunk(" " + po.getVendorPaymentTerms().getVendorPaymentTermsDescription(), cour_7_normal)); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); infoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" Delivery Required By\n", ver_5_normal)); if (po.getDeliveryRequiredDate() != null && po.getDeliveryRequiredDateReason() != null) { p.add(new Chunk(" " + sdf.format(po.getDeliveryRequiredDate()), cour_7_normal)); p.add(new Chunk(" - " + po.getDeliveryRequiredDateReason().getDeliveryRequiredDateReasonDescription(), cour_7_normal)); } else if (po.getDeliveryRequiredDate() != null && po.getDeliveryRequiredDateReason() == null) { p.add(new Chunk(" " + sdf.format(po.getDeliveryRequiredDate()), cour_7_normal)); } else if (po.getDeliveryRequiredDate() == null && po.getDeliveryRequiredDateReason() != null) { p.add(new Chunk(" " + po.getDeliveryRequiredDateReason().getDeliveryRequiredDateReasonDescription(), cour_7_normal)); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); infoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" ", ver_5_normal)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); infoTable.addCell(cell); // Nested table for Order Date, etc. float[] nestedInfoWidths = { 0.50f, 0.50f }; PdfPTable nestedInfoTable = new PdfPTable(nestedInfoWidths); nestedInfoTable.setSplitLate(false); p = new Paragraph(); p.add(new Chunk(" Order Date\n", ver_5_normal)); String orderDate = ""; if (po.getPurchaseOrderInitialOpenTimestamp() != null) { orderDate = sdf.format(po.getPurchaseOrderInitialOpenTimestamp()); } else { // This date isn't set until the first time this document is printed, so will be null the first time; use today's date. orderDate = sdf.format(getDateTimeService().getCurrentSqlDate()); } p.add(new Chunk(" " + orderDate, cour_7_normal)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); nestedInfoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" Customer #\n", ver_5_normal)); if (po.getVendorCustomerNumber() != null) { p.add(new Chunk(" " + po.getVendorCustomerNumber(), cour_7_normal)); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); nestedInfoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" Delivery Instructions\n", ver_5_normal)); if (StringUtils.isNotBlank(po.getDeliveryInstructionText())) { p.add(new Chunk(" " + po.getDeliveryInstructionText(), cour_7_normal)); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); nestedInfoTable.addCell(cell); p = new Paragraph(); p.add(new Chunk(" Contract ID\n", ver_5_normal)); if (po.getVendorContract() != null) { p.add(new Chunk(po.getVendorContract().getVendorContractName(), cour_7_normal)); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); nestedInfoTable.addCell(cell); // Add the nestedInfoTable to the infoTable cell = new PdfPCell(nestedInfoTable); cell.setHorizontalAlignment(Element.ALIGN_CENTER); infoTable.addCell(cell); StringBuffer billToInfo = new StringBuffer(); billToInfo.append("\n"); billToInfo.append(" " + po.getBillingName() + "\n"); billToInfo.append(" " + po.getBillingLine1Address() + "\n"); if (po.getBillingLine2Address() != null) { billToInfo.append(" " + po.getBillingLine2Address() + "\n"); } billToInfo.append(" " + po.getBillingCityName() + ", " + po.getBillingStateCode() + " " + po.getBillingPostalCode() + "\n"); if (po.getBillingPhoneNumber() != null) { billToInfo.append(" " + po.getBillingPhoneNumber()); } if (po.getBillingEmailAddress() != null) { billToInfo.append("\n " + po.getBillingEmailAddress()); } p = new Paragraph(); p.add(new Chunk(" Billing Address", ver_5_normal)); p.add(new Chunk(" " + billToInfo.toString(), cour_7_normal)); p.add(new Chunk("\n Invoice status inquiry: " + statusInquiryUrl, ver_6_normal)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_LEFT); infoTable.addCell(cell); document.add(infoTable); PdfPTable notesStipulationsTable = new PdfPTable(1); notesStipulationsTable.setWidthPercentage(100); notesStipulationsTable.setSplitLate(false); p = new Paragraph(); p.add(new Chunk(" Vendor Note(s)\n", ver_5_normal)); if (po.getVendorNoteText() != null) { p.add(new Chunk(" " + po.getVendorNoteText() + "\n", cour_7_normal)); } PdfPCell tableCell = new PdfPCell(p); tableCell.setHorizontalAlignment(Element.ALIGN_LEFT); tableCell.setVerticalAlignment(Element.ALIGN_TOP); notesStipulationsTable.addCell(tableCell); p = new Paragraph(); p.add(new Chunk(" Vendor Stipulations and Information\n", ver_5_normal)); if ((po.getPurchaseOrderBeginDate() != null) && (po.getPurchaseOrderEndDate() != null)) { p.add(new Chunk(" Order in effect from " + sdf.format(po.getPurchaseOrderBeginDate()) + " to " + sdf.format(po.getPurchaseOrderEndDate()) + ".\n", cour_7_normal)); } Collection<PurchaseOrderVendorStipulation> vendorStipulationsList = po.getPurchaseOrderVendorStipulations(); if (vendorStipulationsList.size() > 0) { StringBuffer vendorStipulations = new StringBuffer(); for (PurchaseOrderVendorStipulation povs : vendorStipulationsList) { vendorStipulations.append(" " + povs.getVendorStipulationDescription() + "\n"); } p.add(new Chunk(" " + vendorStipulations.toString(), cour_7_normal)); } tableCell = new PdfPCell(p); tableCell.setHorizontalAlignment(Element.ALIGN_LEFT); tableCell.setVerticalAlignment(Element.ALIGN_TOP); notesStipulationsTable.addCell(tableCell); document.add(notesStipulationsTable); // ***** Items table ***** LOG.debug("createPdf() items table started."); float[] itemsWidths = { 0.07f, 0.1f, 0.07f, 0.45f, 0.15f, 0.15f }; if (!po.isUseTaxIndicator()) { itemsWidths = ArrayUtils.add(itemsWidths, 0.14f); itemsWidths = ArrayUtils.add(itemsWidths, 0.15f); } PdfPTable itemsTable = new PdfPTable(itemsWidths.length); // itemsTable.setCellsFitPage(false); With this set to true a large cell will // skip to the next page. The default Table behaviour seems to be what we want: // start the large cell on the same page and continue it to the next. itemsTable.setWidthPercentage(100); itemsTable.setWidths(itemsWidths); itemsTable.setSplitLate(false); tableCell = new PdfPCell(new Paragraph("Item\nNo.", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph("Quantity", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph("UOM", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph("Description", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph("Unit Cost", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph("Extended Cost", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); if (!po.isUseTaxIndicator()) { tableCell = new PdfPCell(new Paragraph("Tax Amount", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph("Total Amount", ver_5_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); } Collection<PurchaseOrderItem> itemsList = new ArrayList(); if (isRetransmit) { itemsList = retransmitItems; } else { itemsList = po.getItems(); } for (PurchaseOrderItem poi : itemsList) { if ((poi.getItemType() != null) && (poi.getItemType().isLineItemIndicator() || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_SHIP_AND_HAND_CODE) || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_FREIGHT_CODE) || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ORDER_DISCOUNT_CODE) || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE)) && lineItemDisplaysOnPdf(poi)) { String description = (poi.getItemCatalogNumber() != null) ? poi.getItemCatalogNumber().trim() + " - " : ""; description = description + ((poi.getItemDescription() != null) ? poi.getItemDescription().trim() : ""); if (StringUtils.isNotBlank(description)) { if (poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ORDER_DISCOUNT_CODE) || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE) || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_FREIGHT_CODE) || poi.getItemType().getItemTypeCode() .equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_SHIP_AND_HAND_CODE)) { // If this is a full order discount or trade-in item, we add the item type description to the description. description = poi.getItemType().getItemTypeDescription() + " - " + description; } } // Above the line item types items display the line number; other types don't. if (poi.getItemType().isLineItemIndicator()) { tableCell = new PdfPCell(new Paragraph(poi.getItemLineNumber().toString(), cour_7_normal)); } else { tableCell = new PdfPCell(new Paragraph(" ", cour_7_normal)); } tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); String quantity = (poi.getItemQuantity() != null) ? poi.getItemQuantity().toString() : " "; tableCell = new PdfPCell(new Paragraph(quantity, cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph(poi.getItemUnitOfMeasureCode(), cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_CENTER); itemsTable.addCell(tableCell); tableCell = new PdfPCell(new Paragraph(" " + description, cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_LEFT); itemsTable.addCell(tableCell); String unitPrice = poi.getItemUnitPrice().setScale(4, BigDecimal.ROUND_HALF_UP).toString(); tableCell = new PdfPCell(new Paragraph(unitPrice + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); tableCell = new PdfPCell( new Paragraph(numberFormat.format(poi.getExtendedPrice()) + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); if (!po.isUseTaxIndicator()) { KualiDecimal taxAmount = poi.getItemTaxAmount(); taxAmount = taxAmount == null ? KualiDecimal.ZERO : taxAmount; tableCell = new PdfPCell(new Paragraph(numberFormat.format(taxAmount) + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); tableCell = new PdfPCell( new Paragraph(numberFormat.format(poi.getTotalAmount()) + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); } } } // Blank line before totals itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); if (!po.isUseTaxIndicator()) { itemsTable.addCell(" "); itemsTable.addCell(" "); } //Next Line if (!po.isUseTaxIndicator()) { //Print Total Prior to Tax itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); tableCell = new PdfPCell(new Paragraph("Total Prior to Tax: ", ver_10_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); itemsTable.addCell(tableCell); itemsTable.addCell(" "); KualiDecimal totalDollarAmount = new KualiDecimal(BigDecimal.ZERO); if (po instanceof PurchaseOrderRetransmitDocument) { totalDollarAmount = ((PurchaseOrderRetransmitDocument) po) .getTotalPreTaxDollarAmountForRetransmit(); } else { totalDollarAmount = po.getTotalPreTaxDollarAmount(); } tableCell = new PdfPCell(new Paragraph(numberFormat.format(totalDollarAmount) + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); //Print Total Tax itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); tableCell = new PdfPCell(new Paragraph("Total Tax: ", ver_10_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); itemsTable.addCell(tableCell); itemsTable.addCell(" "); totalDollarAmount = new KualiDecimal(BigDecimal.ZERO); if (po instanceof PurchaseOrderRetransmitDocument) { totalDollarAmount = ((PurchaseOrderRetransmitDocument) po).getTotalTaxDollarAmountForRetransmit(); } else { totalDollarAmount = po.getTotalTaxAmount(); } tableCell = new PdfPCell(new Paragraph(numberFormat.format(totalDollarAmount) + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); } // Totals line; first 3 cols empty itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); if (!po.isUseTaxIndicator()) { itemsTable.addCell(" "); itemsTable.addCell(" "); } tableCell = new PdfPCell(new Paragraph("Total order amount: ", ver_10_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); itemsTable.addCell(tableCell); itemsTable.addCell(" "); KualiDecimal totalDollarAmount = new KualiDecimal(BigDecimal.ZERO); if (po instanceof PurchaseOrderRetransmitDocument) { totalDollarAmount = ((PurchaseOrderRetransmitDocument) po).getTotalDollarAmountForRetransmit(); } else { totalDollarAmount = po.getTotalDollarAmount(); } tableCell = new PdfPCell(new Paragraph(numberFormat.format(totalDollarAmount) + " ", cour_7_normal)); tableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tableCell.setNoWrap(true); itemsTable.addCell(tableCell); // Blank line after totals itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); itemsTable.addCell(" "); if (!po.isUseTaxIndicator()) { itemsTable.addCell(" "); itemsTable.addCell(" "); } document.add(itemsTable); // Contract language. LOG.debug("createPdf() contract language started."); document.add(new Paragraph(contractLanguage, ver_6_normal)); document.add(new Paragraph("\n", ver_6_normal)); // ***** Signatures table ***** LOG.debug("createPdf() signatures table started."); float[] signaturesWidths = { 0.30f, 0.70f }; PdfPTable signaturesTable = new PdfPTable(signaturesWidths); signaturesTable.setWidthPercentage(100); signaturesTable.setHorizontalAlignment(Element.ALIGN_CENTER); signaturesTable.setSplitLate(false); // Director signature and "for more info" line; only on APOs if (po.getPurchaseOrderAutomaticIndicator()) { // Empty cell. cell = new PdfPCell(new Paragraph(" ", cour_7_normal)); cell.setBorderWidth(0); signaturesTable.addCell(cell); //boolean displayRequestorEmail = true; //SpringContext.getBean(ParameterService.class).getIndicatorParameter(PurchaseOrderDocument.class, PurapParameterConstants.DISPLAY_REQUESTOR_EMAIL_ADDRESS_ON_PDF_IND); if (StringUtils.isBlank(po.getInstitutionContactName()) || StringUtils.isBlank(po.getInstitutionContactPhoneNumber()) || StringUtils.isBlank(po.getInstitutionContactEmailAddress())) { //String emailAddress = displayRequestorEmail ? " " + po.getRequestorPersonEmailAddress() : ""; //p = new Paragraph("For more information contact: " + po.getRequestorPersonName() + " " + po.getRequestorPersonPhoneNumber() + emailAddress, cour_7_normal); p = new Paragraph( "For more information contact: " + po.getRequestorPersonName() + " " + po.getRequestorPersonPhoneNumber() + " " + po.getRequestorPersonEmailAddress(), cour_7_normal); } else { //String emailAddress = displayRequestorEmail ? " " + po.getInstitutionContactEmailAddress() : ""; //p = new Paragraph("For more information contact: " + po.getInstitutionContactName() + " " + po.getInstitutionContactPhoneNumber() + emailAddress, cour_7_normal); p = new Paragraph("For more information contact: " + po.getInstitutionContactName() + " " + po.getInstitutionContactPhoneNumber() + " " + po.getInstitutionContactEmailAddress(), cour_7_normal); } cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); signaturesTable.addCell(cell); Image directorSignature = null; if (StringUtils.isNotBlank(directorSignatureImage)) { try { directorSignature = Image.getInstance(directorSignatureImage); } catch (FileNotFoundException e) { LOG.info("The director signature image [" + directorSignatureImage + "] is not available. Defaulting to the default image."); } } if (directorSignature == null) { // an empty cell if the contract manager signature image is not available. cell = new PdfPCell(); } else { directorSignature.scalePercent(30, 30); cell = new PdfPCell(directorSignature, false); } cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setBorderWidth(0); signaturesTable.addCell(cell); // Empty cell. cell = new PdfPCell(new Paragraph(" ", cour_7_normal)); cell.setBorderWidth(0); signaturesTable.addCell(cell); } // Director name and title; on every pdf. p = new Paragraph(); if (LOG.isDebugEnabled()) { LOG.debug("createPdf() directorName parameter: " + directorName); } if (po.getPurchaseOrderAutomaticIndicator()) { // The signature is on the pdf; use small font. p.add(new Chunk(directorName, ver_6_normal)); } else { // The signature isn't on the pdf; use larger font. p.add(new Chunk(directorName, ver_10_normal)); } p.add(new Chunk("\n" + directorTitle, ver_4_normal)); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidth(0); signaturesTable.addCell(cell); // Contract manager signature, name and phone; only on non-APOs if (!po.getPurchaseOrderAutomaticIndicator()) { Image contractManagerSignature = null; if (StringUtils.isNotBlank(contractManagerSignatureImage)) { try { contractManagerSignature = Image.getInstance(contractManagerSignatureImage); } catch (IOException e) { LOG.info("The contract manager image [" + contractManagerSignatureImage + "] is not available. Defaulting to the default image."); } } if (contractManagerSignature == null) { // an empty cell if the contract manager signature image is not available. cell = new PdfPCell(); } else { contractManagerSignature.scalePercent(15, 15); cell = new PdfPCell(contractManagerSignature, false); } cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setBorderWidth(0); signaturesTable.addCell(cell); // Empty cell. cell = new PdfPCell(new Paragraph(" ", ver_10_normal)); cell.setBorderWidth(0); signaturesTable.addCell(cell); cell = new PdfPCell(new Paragraph(po.getContractManager().getContractManagerName() + " " + po.getContractManager().getContractManagerPhoneNumber(), cour_7_normal)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidth(0); signaturesTable.addCell(cell); } else { // Empty cell. cell = new PdfPCell(new Paragraph(" ", ver_10_normal)); cell.setBorderWidth(0); signaturesTable.addCell(cell); } document.add(signaturesTable); document.close(); LOG.debug("createPdf()pdf document closed."); }
From source file:org.kuali.kfs.module.purap.pdf.PurchaseOrderQuotePdf.java
License:Open Source License
/** * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable with relevant contents * and set its logo image if there is a logoImage to be used. * * @param writer The PdfWriter for this document. * @param document The document./*from ww w.j av a 2 s . c o m*/ * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ @Override public void onOpenDocument(PdfWriter writer, Document document) { LOG.debug("onOpenDocument() started."); try { float[] headerWidths = { 0.20f, 0.60f, 0.20f }; headerTable = new PdfPTable(headerWidths); headerTable.setWidthPercentage(100); headerTable.setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.getDefaultCell().setBorderWidth(0); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER); if (StringUtils.isNotBlank(logoImage)) { logo = Image.getInstance(logoImage); logo.scalePercent(3, 3); headerTable.addCell(new Phrase(new Chunk(logo, 0, 0))); } else { // if we don't use images headerTable.addCell(new Phrase(new Chunk(""))); } PdfPCell cell; cell = new PdfPCell(new Paragraph("REQUEST FOR QUOTATION\nTHIS IS NOT AN ORDER", ver_17_normal)); cell.setBorderWidth(0); cell.setHorizontalAlignment(Element.ALIGN_CENTER); headerTable.addCell(cell); Paragraph p = new Paragraph(); p.add(new Chunk("\n R.Q. Number: ", ver_8_bold)); p.add(new Chunk(po.getPurapDocumentIdentifier() + "\n", cour_10_normal)); cell = new PdfPCell(p); cell.setBorderWidth(0); headerTable.addCell(cell); // initialization of the template tpl = writer.getDirectContent().createTemplate(100, 100); // initialization of the font helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:org.kuali.kra.irb.actions.print.ProtocolPrintWatermark.java
License:Educational Community License
/** * This method for getting the watermark from the database. * /* w w w . jav a2 s .c o m*/ * @param statusCode is the status of the protocol * @return WatermarkBean LOG Exception * @see org.kuali.kra.util.watermark.WatermarkDao#getProtocolWatermarkBeanObject(java.lang.String) */ @SuppressWarnings("unchecked") public WatermarkBean getProtocolWatermarkBeanObject(String protocolStatusCode) { WatermarkBean watermarkBean = new WatermarkBean(); Watermark watermark = null; Map<String, Object> fields = new HashMap<String, Object>(); fields.put("statusCode", protocolStatusCode); Collection<Watermark> watermarks = getBusinessObjectService().findMatching(Watermark.class, fields); if (watermarks != null && watermarks.size() > 0) { watermark = watermarks.iterator().next(); } if (watermark != null && watermark.isWatermarkStatus()) { try { String watermarkFontSize = watermark.getFontSize() == null ? WatermarkConstants.DEFAULT_FONT_SIZE_CHAR : watermark.getFontSize(); String watermarkFontColour = watermark.getFontColor() == null ? WatermarkConstants.FONT_COLOR : watermark.getFontColor(); watermarkBean.setType(watermark.getWatermarkType() == null ? WatermarkConstants.WATERMARK_TYPE_TEXT : watermark.getWatermarkType()); watermarkBean .setFont(getWatermarkFont(WatermarkConstants.FONT, watermarkFontSize, watermarkFontColour)); watermarkBean.setText(watermark.getWatermarkText()); if (watermarkBean.getType().equals(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { watermarkBean.setText(watermark.getFileName()); byte[] imageData = watermark.getAttachmentContent(); if (imageData != null) { Image imageFile = Image.getInstance(imageData); watermarkBean.setFileImage(imageFile); } } } catch (Exception e) { LOG.error("Exception Occured in (ProtocolPrintWatermark) :", e); } return watermarkBean; } return null; }