List of usage examples for com.lowagie.text Document close
boolean close
To view the source code for com.lowagie.text Document close.
Click Source Link
From source file:com.efficio.fieldbook.service.LabelPrintingServiceImpl.java
License:Open Source License
/** * Gets the cell height./*from ww w .j av a 2s. com*/ * * @param numberOfRowsPerPage the number of rows per page * @param pageSizeId the page size id * @return the cell height */ /* private float getCellHeight(int numberOfRowsPerPage, int pageSizeId){ if(pageSizeId == AppConstants.SIZE_OF_PAPER_A4){ if(numberOfRowsPerPage == 7){ return 108f; //ok }else if(numberOfRowsPerPage == 8){ return 97f;//ok }else if(numberOfRowsPerPage == 10){ return 72.5f; } }else{ if(numberOfRowsPerPage == 7){ return 108f; //ok }else if(numberOfRowsPerPage == 8){ return 98.1f;//ok }else if(numberOfRowsPerPage == 10){ return 72.5f;//ok } } return 0f; } */ /* (non-Javadoc) * @see com.efficio.fieldbook.service.api.LabelPrintingService#generateLabels(com.efficio.fieldbook.web.fieldmap.bean.UserFieldmap) */ @Override public String generatePDFLabels(List<StudyTrialInstanceInfo> trialInstances, UserLabelPrinting userLabelPrinting, ByteArrayOutputStream baos) throws MiddlewareQueryException { // setUserLabelPrinting(form.getUserLabelPrinting()); int pageSizeId = Integer.parseInt(userLabelPrinting.getSizeOfLabelSheet()); int numberOfLabelPerRow = Integer.parseInt(userLabelPrinting.getNumberOfLabelPerRow()); int numberofRowsPerPageOfLabel = Integer.parseInt(userLabelPrinting.getNumberOfRowsPerPageOfLabel()); int totalPerPage = numberOfLabelPerRow * numberofRowsPerPageOfLabel; String leftSelectedFields = userLabelPrinting.getLeftSelectedLabelFields(); String rightSelectedFields = userLabelPrinting.getRightSelectedLabelFields(); String barcodeNeeded = userLabelPrinting.getBarcodeNeeded(); String firstBarcodeField = userLabelPrinting.getFirstBarcodeField(); String secondBarcodeField = userLabelPrinting.getSecondBarcodeField(); String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField(); String currentDate = DateUtil.getCurrentDate(); // String fileName = currentDate + ".pdf"; String fileName = userLabelPrinting.getFilenameDLLocation(); try { FileOutputStream fileOutputStream = new FileOutputStream(fileName); try { // Image image1 = Image.getInstance(imageLocation); // PageSize.A4 LabelPaper paper = LabelPaperFactory.generateLabelPaper(numberOfLabelPerRow, numberofRowsPerPageOfLabel, pageSizeId); Rectangle pageSize = PageSize.LETTER; if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4.getInt()) pageSize = PageSize.A4; Document document = new Document(pageSize); /* * 2, 2, 33.3f, 5 * 15, 0, 42, 5 * 10, 0, 17, 5 * 10, 0, 17, 5 * 5, 0, 0, 5 * 15, 0, 37, 5 * 10, 0, 17, 5 if (pageSizeId == AppConstants.SIZE_OF_PAPER_LETTER) { if (numberofRowsPerPageOfLabel == 7) document.setMargins(10, 0, 17, 5); else if (numberofRowsPerPageOfLabel == 8) document.setMargins(5, 0, 0, 5); else if (numberofRowsPerPageOfLabel == 10) document.setMargins(2, 2, 33.3f, 5); } else if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4) { if (numberofRowsPerPageOfLabel == 7) document.setMargins(15, 0, 42, 5); else if (numberofRowsPerPageOfLabel == 8) document.setMargins(15, 0, 37, 5); else if (numberofRowsPerPageOfLabel == 10) document.setMargins(6, 2, 17.5f, 5); } */ //float marginLeft, float marginRight, float marginTop, float marginBottom document.setMargins(paper.getMarginLeft(), paper.getMarginRight(), paper.getMarginTop(), paper.getMarginBottom()); // PdfWriter writer = PdfWriter.getInstance(document, baos); PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); // step 3 document.open(); // step 4 PdfContentByte canvas = writer.getDirectContent(); int i = 0; int fixTableRowSize = numberOfLabelPerRow; PdfPTable table = new PdfPTable(fixTableRowSize); // table.writeSelectedRows(0, -1, 10, 12, canvas); float columnWidthSize = 265f;// 180f; float[] widthColumns = new float[fixTableRowSize]; for (int counter = 0; counter < widthColumns.length; counter++) { widthColumns[counter] = columnWidthSize; } table.setWidths(widthColumns); table.setWidthPercentage(100); int width = 600; int height = 75; List<File> filesToBeDeleted = new ArrayList<File>(); //float cellHeight = getCellHeight(numberofRowsPerPageOfLabel, pageSizeId); float cellHeight = paper.getCellHeight(); for (StudyTrialInstanceInfo trialInstance : trialInstances) { FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance(); Map<String, String> moreFieldInfo = new HashMap<String, String>(); moreFieldInfo.put("locationName", fieldMapTrialInstanceInfo.getLocationName()); moreFieldInfo.put("blockName", fieldMapTrialInstanceInfo.getBlockName()); moreFieldInfo.put("selectedName", trialInstance.getFieldbookName()); moreFieldInfo.put("trialInstanceNumber", fieldMapTrialInstanceInfo.getTrialInstanceNo()); for (FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) { i++; String barcodeLabel = generateBarcodeField(moreFieldInfo, fieldMapLabel, firstBarcodeField, secondBarcodeField, thirdBarcodeField, barcodeNeeded); if ("0".equalsIgnoreCase(barcodeNeeded)) { barcodeLabel = " "; } BitMatrix bitMatrix = new Code128Writer().encode(barcodeLabel, BarcodeFormat.CODE_128, width, height, null); String imageLocation = System.getProperty("user.home") + "/" + Math.random() + ".png"; File imageFile = new File(imageLocation); FileOutputStream fout = new FileOutputStream(imageFile); MatrixToImageWriter.writeToStream(bitMatrix, "png", fout); filesToBeDeleted.add(imageFile); Image mainImage = Image.getInstance(imageLocation); PdfPCell cell = new PdfPCell(); cell.setFixedHeight(cellHeight); cell.setNoWrap(false); cell.setPadding(5f); cell.setPaddingBottom(1f); PdfPTable innerImageTableInfo = new PdfPTable(1); innerImageTableInfo.setWidths(new float[] { 1 }); innerImageTableInfo.setWidthPercentage(82); PdfPCell cellImage = new PdfPCell(); if ("1".equalsIgnoreCase(barcodeNeeded)) { cellImage.addElement(mainImage); } else { cellImage.addElement(new Paragraph(" ")); } cellImage.setBorder(Rectangle.NO_BORDER); cellImage.setBackgroundColor(Color.white); cellImage.setPadding(1.5f); innerImageTableInfo.addCell(cellImage); //float fontSize = 6.8f; float fontSize = paper.getFontSize(); //if (numberofRowsPerPageOfLabel == 10) // fontSize = 4.8f; Font fontNormal = FontFactory.getFont("Arial", fontSize, Font.NORMAL); // cell.addElement(mainImage); cell.addElement(innerImageTableInfo); cell.addElement(new Paragraph()); for (int row = 0; row < 5; row++) { if (row == 0) { PdfPTable innerDataTableInfo = new PdfPTable(1); innerDataTableInfo.setWidths(new float[] { 1 }); innerDataTableInfo.setWidthPercentage(85); Font fontNormalData = FontFactory.getFont("Arial", 5.0f, Font.NORMAL); PdfPCell cellInnerData = new PdfPCell(new Phrase(barcodeLabel, fontNormalData)); cellInnerData.setBorder(Rectangle.NO_BORDER); cellInnerData.setBackgroundColor(Color.white); cellInnerData.setPaddingBottom(0.2f); cellInnerData.setPaddingTop(0.2f); cellInnerData.setHorizontalAlignment(Element.ALIGN_MIDDLE); innerDataTableInfo.addCell(cellInnerData); innerDataTableInfo.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.addElement(innerDataTableInfo); } PdfPTable innerTableInfo = new PdfPTable(2); innerTableInfo.setWidths(new float[] { 1, 1 }); innerTableInfo.setWidthPercentage(85); String leftText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel, leftSelectedFields, row); PdfPCell cellInnerLeft = new PdfPCell(new Paragraph(leftText, fontNormal)); cellInnerLeft.setBorder(Rectangle.NO_BORDER); cellInnerLeft.setBackgroundColor(Color.white); cellInnerLeft.setPaddingBottom(0.5f); cellInnerLeft.setPaddingTop(0.5f); innerTableInfo.addCell(cellInnerLeft); String rightText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel, rightSelectedFields, row); PdfPCell cellInnerRight = new PdfPCell(new Paragraph(rightText, fontNormal)); cellInnerRight.setBorder(Rectangle.NO_BORDER); cellInnerRight.setBackgroundColor(Color.white); cellInnerRight.setPaddingBottom(0.5f); cellInnerRight.setPaddingTop(0.5f); innerTableInfo.addCell(cellInnerRight); cell.addElement(innerTableInfo); } cell.setBorder(Rectangle.NO_BORDER); cell.setBackgroundColor(Color.white); //cell.setBorderColor(Color.BLUE); table.addCell(cell); if (i % numberOfLabelPerRow == 0) { // we go the next line int needed = fixTableRowSize - numberOfLabelPerRow; for (int neededCount = 0; neededCount < needed; neededCount++) { PdfPCell cellNeeded = new PdfPCell(); cellNeeded.setBorder(Rectangle.NO_BORDER); cellNeeded.setBackgroundColor(Color.white); table.addCell(cellNeeded); } table.completeRow(); if (numberofRowsPerPageOfLabel == 10) { //table.setSpacingAfter(9f); table.setSpacingAfter(paper.getSpacingAfter()); } document.add(table); table = new PdfPTable(fixTableRowSize); table.setWidths(widthColumns); table.setWidthPercentage(100); } if (i % totalPerPage == 0) { // we go the next page document.newPage(); } fout.flush(); fout.close(); } } // we need to add the last row if (i % numberOfLabelPerRow != 0) { // we go the next line int needed = fixTableRowSize - numberOfLabelPerRow; int remaining = numberOfLabelPerRow - (i % numberOfLabelPerRow); for (int neededCount = 0; neededCount < remaining; neededCount++) { PdfPCell cellNeeded = new PdfPCell(); cellNeeded.setBorder(Rectangle.NO_BORDER); cellNeeded.setBackgroundColor(Color.white); table.addCell(cellNeeded); } table.completeRow(); if (numberofRowsPerPageOfLabel == 10) { table.setSpacingAfter(paper.getSpacingAfter()); } document.add(table); table = new PdfPTable(fixTableRowSize); table.setWidths(widthColumns); table.setWidthPercentage(100); } document.close(); for (File file : filesToBeDeleted) { file.delete(); } fileOutputStream.close(); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } } catch (WriterException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } return fileName; }
From source file:com.efficio.fieldbook.web.demo.controller.BarCodeController.java
License:Open Source License
/** * Upload file./* w ww .ja va 2 s. c om*/ * * @param uploadForm the upload form * @param result the result * @param model the model * @return the string */ @ResponseBody @RequestMapping(method = RequestMethod.POST) public String uploadFile(@ModelAttribute("barCodeForm") BarCodeForm barCodeForm, BindingResult result, Model model, HttpServletResponse response) { int width = 60; int height = 48; String delimeter = "|"; StringBuilder barCodeString = new StringBuilder(); barCodeString.append(barCodeForm.getEntryNo()).append(delimeter).append(barCodeForm.getGid()) .append(delimeter).append(barCodeForm.getDesignation()).append(delimeter) .append(barCodeForm.getName()).append(delimeter).append(barCodeForm.getRep()).append(delimeter) .append(barCodeForm.getColumn()).append(delimeter).append(barCodeForm.getRange()); BitMatrix bitMatrix; try { String barCodeLabel = "3|SM114-1A-1-1-1B"; //barCodeLabel = barCodeString.toString(); bitMatrix = new Code128Writer().encode(barCodeLabel, BarcodeFormat.CODE_128, width, height, null); String imageLocation = Math.random() + ".png"; //"src/test/resources/barcode/zxing_barcode.png"; MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File(imageLocation))); String currentDate = DateUtil.getCurrentDate(); String fileName = currentDate + ".doc"; response.setHeader("Content-disposition", "attachment; filename=" + fileName); File xls = new File(fileName); // the selected name + current date FileInputStream in; try { Image image1 = Image.getInstance(imageLocation); //image1.scalePercent(50); //image1.setAbsolutePosition(10f, 10f); //document.add(image1); //PageSize.A4 Document document = new Document(PageSize.LETTER); // step 2 PdfWriter.getInstance(document, new FileOutputStream(fileName)); // step 3 document.open(); // step 4 // we'll use 4 images in this example /* Image[] img = { Image.getInstance(String.format(RESOURCE, "0120903")), Image.getInstance(String.format(RESOURCE, "0290334")), Image.getInstance(String.format(RESOURCE, "0376994")), Image.getInstance(String.format(RESOURCE, "0348150")) };*/ PdfPTable table = new PdfPTable(4); table.setWidthPercentage(100); // first movie table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM); Phrase phrase = new Phrase(); phrase.add("Entry # " + barCodeForm.getEntryNo()); phrase.add("\n"); phrase.add("Designation " + barCodeForm.getDesignation()); phrase.add("\n"); phrase.add("Rep " + barCodeForm.getRep()); phrase.add("\n"); phrase.add("GID " + barCodeForm.getGid()); phrase.add("\n"); phrase.add("Trial/Nursery Name " + barCodeForm.getName()); phrase.add("\n"); phrase.add("Col " + barCodeForm.getColumn()); phrase.add("\n"); phrase.add("Range " + barCodeForm.getRange()); table.addCell(phrase); // we add the image with addCell() table.addCell(image1); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell("X-Men: The Last Stand"); // we add the image with addCell() table.addCell(image1); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell("X-Men: The Last Stand"); // we add the image with addCell() table.addCell(image1); // we complete the table (otherwise the last row won't be rendered) table.completeRow(); document.add(table); document.close(); in = new FileInputStream(xls); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; // use bigger if you want int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } return ""; } catch (WriterException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } return show(barCodeForm, model); }
From source file:com.eteks.sweethome3d.swing.HomePDFPrinter.java
License:Open Source License
/** * Writes to <code>outputStream</code> the print of a home in PDF format. *///from ww w.ja v a 2 s . co m public void write(OutputStream outputStream) throws IOException { PageFormat pageFormat = HomePrintableComponent.getPageFormat(this.home.getPrint()); Document pdfDocument = new Document( new Rectangle((float) pageFormat.getWidth(), (float) pageFormat.getHeight())); try { // Get a PDF writer that will write to the given PDF output stream PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, outputStream); pdfDocument.open(); // Set PDF document description pdfDocument.addAuthor(System.getProperty("user.name", "")); String pdfDocumentCreator = this.preferences.getLocalizedString(HomePDFPrinter.class, "pdfDocument.creator"); pdfDocument.addCreator(pdfDocumentCreator); pdfDocument.addCreationDate(); String homeName = this.home.getName(); if (homeName != null) { pdfDocument.addTitle(this.controller.getContentManager().getPresentationName(homeName, ContentManager.ContentType.PDF)); } PdfContentByte pdfContent = pdfWriter.getDirectContent(); HomePrintableComponent printableComponent = new HomePrintableComponent(this.home, this.controller, this.defaultFont); // Print each page for (int page = 0, pageCount = printableComponent.getPageCount(); page < pageCount; page++) { // Check current thread isn't interrupted if (Thread.interrupted()) { throw new InterruptedIOException(); } PdfTemplate pdfTemplate = pdfContent.createTemplate((float) pageFormat.getWidth(), (float) pageFormat.getHeight()); Graphics g = pdfTemplate.createGraphicsShapes((float) pageFormat.getWidth(), (float) pageFormat.getHeight()); printableComponent.print(g, pageFormat, page); pdfContent.addTemplate(pdfTemplate, 0, 0); g.dispose(); if (page != pageCount - 1) { pdfDocument.newPage(); } } pdfDocument.close(); } catch (DocumentException ex) { IOException exception = new IOException("Couldn't print to PDF"); exception.initCause(ex); throw exception; } catch (InterruptedPrinterException ex) { throw new InterruptedIOException("Print to PDF interrupted"); } catch (PrinterException ex) { IOException exception = new IOException("Couldn't print to PDF"); exception.initCause(ex); throw exception; } }
From source file:com.exam.server.ConvertPDF.java
public ConvertPDF(ArrayList<DeviceDTO> input) { try {/* ww w . ja v a 2 s .c o m*/ Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE)); System.out.println("opening document " + FILE); document.open(); addMetaData(document); addTitlePage(document); addContent(document, input); addPieChart(generatePieChart(input), 500, 400, writer); document.close(); System.out.println("closing document " + FILE); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.exam.server.ConvertPDF.java
public static void main(String[] args) { try {// ww w . j a v a 2 s . c o m ArrayList<DeviceDTO> input = new ArrayList<DeviceDTO>(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE)); System.out.println("opening document " + FILE); document.open(); addMetaData(document); addTitlePage(document); addContent(document, input); addPieChart(generatePieChart(input), 500, 400, writer); document.close(); System.out.println("closing document " + FILE); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.example.dwr.simple.UploadDownload.java
License:Apache License
/** * Generates a PDF file with the given text * http://itext.ugent.be/itext-in-action/ * @return A PDF file as a byte array//from ww w . ja v a 2s. c o m */ public FileTransfer downloadPdfFile(String contents) throws Exception { if (contents == null || contents.length() == 0) { contents = "[BLANK]"; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, buffer); document.addCreator("DWR.war using iText"); document.open(); document.add(new Paragraph(contents)); document.close(); return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray()); }
From source file:com.foc.vaadin.FPrint.java
License:Apache License
public FPrint(Stack<Component> stack) { Document document = null; try {/*from w w w . j a v a 2 s . c o m*/ document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter.getInstance(document, os); document.open(); //////////////////////////////////////// String value = null; String caption = null; while (!stack.isEmpty()) { Component comp = stack.pop(); if (comp instanceof FVTextField) { caption = ((FVTextField) comp).getCaption(); value = (String) ((FVTextField) comp).getValue(); } document.add(new Paragraph("\n" + caption + ": " + value)); } //////////////////////////////////////// Paragraph pp = new Paragraph(); // Chapter ch = new Chapter(); // ch.addSection(pp); } catch (Exception e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } } }
From source file:com.geek.tutorial.itext.acroform.ListFieldForm.java
License:Open Source License
public ListFieldForm() throws Exception { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("ListFieldForm.pdf")); document.open();//from w w w .j av a 2 s. com // Code 1 String options[] = { "PS3", "XBOX 360", "Wii", "PSP", "NDS", "GBA" }; // Code 2 create drop-down list PdfFormField dropDown = PdfFormField.createCombo(writer, true, options, 0); dropDown.setWidget(new Rectangle(50, 785, 120, 800), PdfAnnotation.HIGHLIGHT_INVERT); dropDown.setFieldName("dropDownList"); dropDown.setValueAsString("PS3"); dropDown.setMKBorderColor(Color.BLACK); writer.addAnnotation(dropDown); // Code 3 create scrollable list TextField scrollableList = new TextField(writer, new Rectangle(150, 740, 250, 800), "scrollableList"); scrollableList.setBackgroundColor(Color.WHITE); scrollableList.setBorderColor(Color.BLUE); scrollableList.setBorderWidth(2); scrollableList.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); scrollableList.setFontSize(10); scrollableList.setChoices(options); scrollableList.setChoiceSelection(0); writer.addAnnotation(scrollableList.getListField()); // Code 4 add function and button for showing state writer.addJavaScript( "function showState(){" + "app.alert('DropDown:'+ this.getField('dropDownList').value +'\\n'+" + "'Scrollable List:'+this.getField('scrollableList').value);" + "}"); PushbuttonField push = new PushbuttonField(writer, new Rectangle(70, 710, 140, 730), "pushAction"); push.setBackgroundColor(Color.LIGHT_GRAY); push.setBorderColor(Color.GRAY); push.setText("Show State"); push.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED); push.setTextColor(Color.BLACK); PdfFormField pushbutton = push.getField(); pushbutton.setAction(PdfAction.javaScript("showState()", writer)); writer.addAnnotation(pushbutton); document.close(); }
From source file:com.geek.tutorial.itext.acroform.RadioCheckBoxForm.java
License:Open Source License
public RadioCheckBoxForm() throws Exception { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("RadioCheckBoxForm.pdf")); document.open();/*from w w w . j a va 2s . com*/ PdfContentByte cb = writer.getDirectContent(); BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); Rectangle rect; // Code 1 create radio button String[] radios = { "Radio1", "Radio2", "Radio3" }; PdfFormField radioField = PdfFormField.createRadioButton(writer, true); radioField.setFieldName("radioField"); radioField.setValueAsName(radios[0]); for (int i = 0; i < radios.length; i++) { rect = new Rectangle(40, 815 - i * 30, 60, 797 - i * 30); addRadioButton(writer, rect, radioField, radios[i], i == 0); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(Element.ALIGN_LEFT, radios[i], 70, 802 - i * 30, 0); cb.endText(); } writer.addAnnotation(radioField); // Code 2 create checkbox button String[] options = { "Check1", "Check2", "Check3" }; for (int i = 0; i < options.length; i++) { rect = new Rectangle(160, 815 - i * 30, 180, 797 - i * 30); addCheckbox(writer, rect, options[i]); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(Element.ALIGN_LEFT, options[i], 190, 802 - i * 30, 0); cb.endText(); } // Code 3 add function and button for showing state writer.addJavaScript( "function showState(){" + "app.alert('Radio:'+ this.getField('radioField').value +'\\n\\n'+" + "'Check1:'+this.getField('Check1').value +'\\n'+" + "'Check2:'+this.getField('Check2').value +'\\n'+" + "'Check3:'+this.getField('Check3').value);" + "}"); PushbuttonField push = new PushbuttonField(writer, new Rectangle(80, 710, 150, 730), "pushAction"); push.setBackgroundColor(Color.LIGHT_GRAY); push.setBorderColor(Color.GRAY); push.setText("Show State"); push.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED); push.setTextColor(Color.BLACK); PdfFormField pushbutton = push.getField(); pushbutton.setAction(PdfAction.javaScript("showState()", writer)); writer.addAnnotation(pushbutton); document.close(); }
From source file:com.geek.tutorial.itext.acroform.TextFieldForm.java
License:Open Source License
public TextFieldForm() throws Exception { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf")); document.open();//from w ww .j av a 2 s.c o m PdfPTable table = new PdfPTable(2); table.getDefaultCell().setPadding(5f); // Code 1, will only affect empty field table.setHorizontalAlignment(Element.ALIGN_LEFT); PdfPCell cell; // Code 2, add name TextField table.addCell("Name"); TextField nameField = new TextField(writer, new Rectangle(0, 0, 200, 10), "nameField"); nameField.setBackgroundColor(Color.WHITE); nameField.setBorderColor(Color.BLACK); nameField.setBorderWidth(1); nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); nameField.setText(""); nameField.setAlignment(Element.ALIGN_LEFT); nameField.setOptions(TextField.REQUIRED); cell = new PdfPCell(); cell.setMinimumHeight(10); cell.setCellEvent(new FieldCell(nameField.getTextField(), 200, writer)); table.addCell(cell); // force upper case javascript writer.addJavaScript("var nameField = this.getField('nameField');" + "nameField.setAction('Keystroke'," + "'forceUpperCase()');" + "" + "function forceUpperCase(){" + "if(!event.willCommit)event.change = " + "event.change.toUpperCase();" + "}"); // Code 3, add empty row table.addCell(""); table.addCell(""); // Code 4, add age TextField table.addCell("Age"); TextField ageComb = new TextField(writer, new Rectangle(0, 0, 30, 10), "ageField"); ageComb.setBorderColor(Color.BLACK); ageComb.setBorderWidth(1); ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); ageComb.setText("12"); ageComb.setAlignment(Element.ALIGN_RIGHT); ageComb.setMaxCharacterLength(2); ageComb.setOptions(TextField.COMB | TextField.DO_NOT_SCROLL); cell = new PdfPCell(); cell.setMinimumHeight(10); cell.setCellEvent(new FieldCell(ageComb.getTextField(), 30, writer)); table.addCell(cell); // validate age javascript writer.addJavaScript("var ageField = this.getField('ageField');" + "ageField.setAction('Validate','checkAge()');" + "function checkAge(){" + "if(event.value < 12){" + "app.alert('Warning! Applicant\\'s age can not" + " be younger than 12.');" + "event.value = 12;" + "}}"); // add empty row table.addCell(""); table.addCell(""); // Code 5, add age TextField table.addCell("Comment"); TextField comment = new TextField(writer, new Rectangle(0, 0, 200, 100), "commentField"); comment.setBorderColor(Color.BLACK); comment.setBorderWidth(1); comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); comment.setText(""); comment.setOptions(TextField.MULTILINE | TextField.DO_NOT_SCROLL); cell = new PdfPCell(); cell.setMinimumHeight(100); cell.setCellEvent(new FieldCell(comment.getTextField(), 200, writer)); table.addCell(cell); // check comment characters length javascript writer.addJavaScript("var commentField = " + "this.getField('commentField');" + "commentField" + ".setAction('Keystroke','checkLength()');" + "function checkLength(){" + "if(!event.willCommit && " + "event.value.length > 100){" + "app.alert('Warning! Comment can not " + "be more than 100 characters.');" + "event.change = '';" + "}}"); // add empty row table.addCell(""); table.addCell(""); // Code 6, add submit button PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(0, 0, 35, 15), "submitPOST"); submitBtn.setBackgroundColor(Color.GRAY); submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED); submitBtn.setText("POST"); submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT); PdfFormField submitField = submitBtn.getField(); submitField.setAction(PdfAction.createSubmitForm("http://www.geek-tutorials.com/java/itext/submit.php", null, PdfAction.SUBMIT_HTML_FORMAT)); cell = new PdfPCell(); cell.setMinimumHeight(15); cell.setCellEvent(new FieldCell(submitField, 35, writer)); table.addCell(cell); // Code 7, add reset button PushbuttonField resetBtn = new PushbuttonField(writer, new Rectangle(0, 0, 35, 15), "reset"); resetBtn.setBackgroundColor(Color.GRAY); resetBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED); resetBtn.setText("RESET"); resetBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT); PdfFormField resetField = resetBtn.getField(); resetField.setAction(PdfAction.createResetForm(null, 0)); cell = new PdfPCell(); cell.setMinimumHeight(15); cell.setCellEvent(new FieldCell(resetField, 35, writer)); table.addCell(cell); document.add(table); document.close(); }