public byte[] make(Firm firm, User user) { /* * make metadata for the document */ Language language = DOC.getLanguage(); SimpleDateFormat sdf = DateFormats.DOT_DATE_FORMAT(); DecimalFormat COMMA_3 = NumberFormats.THREE_AFTER_COMMA(); DecimalFormat COMMA_2 = NumberFormats.TWO_AFTER_COMMA(); DecimalFormat DISCOUNT = NumberFormats.DISCOUNT_FORMAT(); Font TR_12_B = DocumentFonts.TIMES_ROMAN_12_BOLD(); Font TR_12 = DocumentFonts.TIMES_ROMAN_12(); Font TR_10_B = DocumentFonts.TIMES_ROMAN_10_BOLD(); Font TR_10 = DocumentFonts.TIMES_ROMAN_10(); Font TR_10_B_I = DocumentFonts.TIMES_ROMAN_10_BOLD_ITALIC(); Font TR_8_I = DocumentFonts.TIMES_ROMAN_8_ITALIC(); com.itextpdf.text.Document blackBoard = null; com.itextpdf.text.Document finalDocument = null; ByteArrayOutputStream byteOutputStream = null; ByteArrayOutputStream temporaryByteStream = null; PdfReader reader; HeaderFooter pageEvent = new HeaderFooter(firm, false, true); boolean wasError = false; /* * make the document */ try { // make an empty cell and paragraph, going to need them later multiple times PdfPCell emptyCell = new PdfPCell(new Phrase(" ")); emptyCell.setBorder(Rectangle.NO_BORDER); Paragraph emptyParagraph = new Paragraph(" "); /* * First paragraph of the page, included in every page afterwards */ Paragraph pageStartParagraph = new Paragraph(); PdfPTable headerTable = new PdfPTable(3); // table with 3 columns headerTable.setWidths(new int[] {170, 230, 70}); // table column sizes headerTable.setWidthPercentage(100); // Type cell headerTable.addCell( new PdfPCell(new Phrase(language.get("invoice") + ": " + DOC.getFullNumber(), TR_12_B))); // Date cells PdfPCell languageDateCell = new PdfPCell(new Phrase(language.get("date") + ":", TR_10_B)); languageDateCell.setHorizontalAlignment(Element.ALIGN_RIGHT); languageDateCell.setBorder(Rectangle.NO_BORDER); headerTable.addCell(languageDateCell); PdfPCell dateCell = new PdfPCell(new Phrase(DOC.getFormatedDate(), TR_10)); dateCell.setHorizontalAlignment(Element.ALIGN_RIGHT); dateCell.setBorder(Rectangle.NO_BORDER); headerTable.addCell(dateCell); /// Payd in cash cell if (DOC.isPaydInCash()) { PdfPCell paydInCashCell = new PdfPCell(new Phrase(language.get("paydInCash"), TR_10)); paydInCashCell.setBorder(Rectangle.NO_BORDER); headerTable.addCell(paydInCashCell); } else { headerTable.addCell(emptyCell); } // payment requirement cells PdfPCell languagePayReqCell = new PdfPCell(new Phrase(language.get("paymentRequirement") + ":", TR_10)); languagePayReqCell.setHorizontalAlignment(Element.ALIGN_RIGHT); languagePayReqCell.setBorder(Rectangle.NO_BORDER); headerTable.addCell(languagePayReqCell); PdfPCell payReqCell = new PdfPCell(new Phrase(DOC.getValidDue() + " " + language.get("days"), TR_10)); payReqCell.setHorizontalAlignment(Element.ALIGN_RIGHT); payReqCell.setBorder(Rectangle.NO_BORDER); headerTable.addCell(payReqCell); // empty cell headerTable.addCell(emptyCell); // payment due time cells PdfPCell languagePayDueCell = new PdfPCell(new Phrase(language.get("paymentTime") + ":", TR_10_B)); languagePayDueCell.setBorder(Rectangle.NO_BORDER); languagePayDueCell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(languagePayDueCell); Date paymentDueDate = new Date(DOC.getDate().getTime() + (DOC.getValidDue() * 24 * 60 * 60 * 1000L)); PdfPCell payDueCell = new PdfPCell(new Phrase(sdf.format(paymentDueDate), TR_10)); payDueCell.setBorder(Rectangle.NO_BORDER); payDueCell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(payDueCell); // done with header table pageStartParagraph.add(headerTable); pageStartParagraph.add(emptyParagraph); /* * client data */ // buyer and firm data table PdfPTable buyerAndFirmTable = new PdfPTable(2); // table with 2 columns buyerAndFirmTable.setWidthPercentage(100); buyerAndFirmTable.setWidths(new int[] {200, 200}); // set table column sizes // Buyer data Paragraph buyerParagraph = new Paragraph(); buyerParagraph.add(new Phrase(language.get("buyer") + ":", TR_10_B)); buyerParagraph.add(Chunk.NEWLINE); buyerParagraph.add(new Phrase(DOC.getClient().getName(), TR_10)); buyerParagraph.add(Chunk.NEWLINE); buyerParagraph.add(new Phrase(DOC.getClient().getAddress(), TR_10)); buyerParagraph.add(Chunk.NEWLINE); buyerParagraph.add(new Phrase(DOC.getClient().getAdditionalAddress(), TR_10)); buyerParagraph.add(Chunk.NEWLINE); Phrase contactPersonPhrase = new Phrase("", TR_10); contactPersonPhrase.add(new Phrase(language.get("contactPerson") + ":", TR_10_B)); contactPersonPhrase.add( new Phrase(" " + DOC.getClient().getSelectedContactPerson().getName(), TR_10)); buyerParagraph.add(contactPersonPhrase); buyerParagraph.add(Chunk.NEWLINE); buyerParagraph.add(new Phrase(language.get("orderNR") + ": " + DOC.getOrderNR(), TR_10)); // firm data Paragraph firmParagraph = new Paragraph(); firmParagraph.add(new Phrase(language.get("seller") + ":", TR_10_B)); firmParagraph.add(Chunk.NEWLINE); firmParagraph.add(new Phrase(firm.getName(), TR_10)); firmParagraph.add(Chunk.NEWLINE); firmParagraph.add(new Phrase(firm.getAddress(), TR_10)); firmParagraph.add(Chunk.NEWLINE); firmParagraph.add(new Phrase("Reg nr " + firm.getRegNR(), TR_10)); firmParagraph.add(Chunk.NEWLINE); firmParagraph.add(new Phrase("KMKR nr " + firm.getKmkr(), TR_10)); firmParagraph.add(Chunk.NEWLINE); firmParagraph.add( new Phrase( firm.getBank() + " IBAN " + firm.getIban() + " SWIFT " + firm.getSwift(), TR_10)); buyerAndFirmTable.addCell(new PdfPCell(buyerParagraph)); buyerAndFirmTable.addCell(new PdfPCell(firmParagraph)); // done with buyer and firm data pageStartParagraph.add(buyerAndFirmTable); /* * Let's make a copy for later page checking */ blackBoard = new com.itextpdf.text.Document(); temporaryByteStream = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(blackBoard, temporaryByteStream); pageEvent.setPageStartParagraph(pageStartParagraph); writer.setPageEvent(pageEvent); blackBoard.open(); /* * First paragraph */ Paragraph firstParagraph = new Paragraph(); /* * Products header table */ PdfPTable productsHeaderRow; int[] productsTableWidths; if (DOC.isShowDiscount()) { productsHeaderRow = new PdfPTable(7); productsTableWidths = new int[] {8, 93, 17, 12, 20, 15, 25}; } else { productsHeaderRow = new PdfPTable(6); productsTableWidths = new int[] {8, 110, 17, 12, 20, 23}; } productsHeaderRow.setWidthPercentage(100); productsHeaderRow.setWidths(productsTableWidths); // products table header row PdfPCell headerNRCell = new PdfPCell(new Phrase(language.get("nr"), TR_12)); headerNRCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerNRCell); productsHeaderRow.addCell(new PdfPCell(new Phrase(language.get("specification"), TR_12))); PdfPCell headerAmountCell = new PdfPCell(new Phrase(language.get("amount"), TR_12)); headerAmountCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerAmountCell); PdfPCell headerUnitCell = new PdfPCell(new Phrase(language.get("unit"), TR_12)); headerUnitCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerUnitCell); PdfPCell headerPriceCell = new PdfPCell(new Phrase(language.get("price"), TR_12)); headerPriceCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerPriceCell); if (DOC.isShowDiscount()) { PdfPCell headerDiscountCell = new PdfPCell(new Phrase(language.get("discount"), TR_12)); headerDiscountCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerDiscountCell); } PdfPCell headerSumCell = new PdfPCell(new Phrase(language.get("sum"), TR_12)); headerSumCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerSumCell); // add all the products double totalSum = 0; int lastPageNumber = 0; boolean firstProductInPage = true; boolean updateBlackBoard = false; for (int i = 0; i < DOC.getProducts().size(); i++) { Product product = DOC.getProducts().get(i); // check the language and make string accordingly String productName = "", productUnit = ""; if (language.getType().equals(Language.TYPE_ESTONIAN)) { productName = product.getName(); productUnit = product.getUnit(); } else if (language.getType().equals(Language.TYPE_ENGLISH)) { productName = product.getE_name(); productUnit = product.getE_unit(); } // each products has a separate table with the same size as header PdfPTable productRow = new PdfPTable(productsHeaderRow.getNumberOfColumns()); productRow.setWidthPercentage(100); productRow.setWidths(productsTableWidths); PdfPCell NRCEll = new PdfPCell(new Phrase("" + (i + 1), TR_10)); NRCEll.setHorizontalAlignment(Element.ALIGN_CENTER); NRCEll.setBorderColor(BaseColor.LIGHT_GRAY); // name cell with additional info PdfPCell nameCell = null; if (product .hasAdditionalInformation()) { // user has added additional information for this product Paragraph nameAndInfoParagraph = new Paragraph(); nameAndInfoParagraph.add(new Phrase(productName, TR_10)); nameAndInfoParagraph.add(Chunk.NEWLINE); nameAndInfoParagraph.add(new Phrase(product.getAdditional_Info(), TR_8_I)); nameCell = new PdfPCell(new Phrase(nameAndInfoParagraph)); } else { nameCell = new PdfPCell(new Phrase(productName, TR_10)); } nameCell.setBorderColor(BaseColor.LIGHT_GRAY); // amount cell PdfPCell amountCell = new PdfPCell(new Phrase(product.getAmount() + "", TR_10)); amountCell.setHorizontalAlignment(Element.ALIGN_CENTER); amountCell.setBorderColor(BaseColor.LIGHT_GRAY); // unit cell PdfPCell unitCell = new PdfPCell(new Phrase(productUnit, TR_10)); unitCell.setHorizontalAlignment(Element.ALIGN_CENTER); unitCell.setBorderColor(BaseColor.LIGHT_GRAY); // price cell PdfPCell priceCell = new PdfPCell(new Phrase(COMMA_3.format(product.getPrice()), TR_10)); priceCell.setHorizontalAlignment(Element.ALIGN_CENTER); priceCell.setBorderColor(BaseColor.LIGHT_GRAY); // discount cell PdfPCell discountCell = null; if (DOC.isShowDiscount()) { discountCell = new PdfPCell(new Phrase(DISCOUNT.format(product.getDiscount()), TR_10)); discountCell.setHorizontalAlignment(Element.ALIGN_CENTER); discountCell.setBorderColor(BaseColor.LIGHT_GRAY); } // sum cell PdfPCell sumCell = new PdfPCell(new Phrase(COMMA_2.format(product.getTotalSum()), TR_10)); sumCell.setHorizontalAlignment(Element.ALIGN_RIGHT); sumCell.setBorderColor(BaseColor.LIGHT_GRAY); // add all the cells productRow.addCell(NRCEll); productRow.addCell(nameCell); productRow.addCell(amountCell); productRow.addCell(unitCell); productRow.addCell(priceCell); if (DOC.isShowDiscount()) { productRow.addCell(discountCell); } productRow.addCell(sumCell); // add the product row to the blackboard blackBoard.add(productRow); /* * check if we changed a page with the last product add, */ int currentPageNumber = writer.getPageNumber(); if (currentPageNumber > lastPageNumber) { blackBoard.add(productsHeaderRow); // add the table header again to the new page blackBoard.add(emptyParagraph); firstProductInPage = true; lastPageNumber++; } if (firstProductInPage) { // first product row needs to have black edges on top productRow.deleteLastRow(); // delete the last row and re-add later with changed color if (currentPageNumber > 1) { // eliminate the possibility of too-long additional info ending up half paged // on old page firstParagraph.add(new Chunk(Chunk.NEXTPAGE)); } firstParagraph.add(emptyParagraph); // empty space between the page header firstParagraph.add(productsHeaderRow); firstProductInPage = false; updateBlackBoard = true; float borderWidth = NRCEll.getBorderWidth(); NRCEll.setUseVariableBorders(true); nameCell.setUseVariableBorders(true); amountCell.setUseVariableBorders(true); unitCell.setUseVariableBorders(true); priceCell.setUseVariableBorders(true); if (DOC.isShowDiscount()) { discountCell.setUseVariableBorders(true); } sumCell.setUseVariableBorders(true); NRCEll.setBorderColorTop(BaseColor.BLACK); nameCell.setBorderColorTop(BaseColor.BLACK); amountCell.setBorderColorTop(BaseColor.BLACK); unitCell.setBorderColorTop(BaseColor.BLACK); priceCell.setBorderColorTop(BaseColor.BLACK); if (DOC.isShowDiscount()) { discountCell.setBorderColorTop(BaseColor.BLACK); } sumCell.setBorderColorTop(BaseColor.BLACK); /* * this is needed, because SOMEWHY color changing also changes the width */ NRCEll.setBorderWidth(borderWidth / 2); nameCell.setBorderWidth(borderWidth / 2); amountCell.setBorderWidth(borderWidth / 2); unitCell.setBorderWidth(borderWidth / 2); priceCell.setBorderWidth(borderWidth / 2); if (DOC.isShowDiscount()) { discountCell.setBorderWidth(borderWidth / 2); } sumCell.setBorderWidth(borderWidth / 2); productRow.addCell(NRCEll); productRow.addCell(nameCell); productRow.addCell(amountCell); productRow.addCell(unitCell); productRow.addCell(priceCell); if (DOC.isShowDiscount()) { productRow.addCell(discountCell); } productRow.addCell(sumCell); } totalSum += product.getTotalSum(); firstParagraph.add(productRow); /* * update the blackBoard, because we added another page to the document, update the page number */ if (updateBlackBoard) { blackBoard.close(); blackBoard = new com.itextpdf.text.Document(); try { temporaryByteStream.close(); } catch (Exception x) { } // close right after done for memory release temporaryByteStream = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(blackBoard, temporaryByteStream); pageEvent.resetPagesTotal(); writer.setPageEvent(pageEvent); blackBoard.open(); blackBoard.add(firstParagraph); updateBlackBoard = false; } } /* * last paragraph, includes page end information */ Paragraph lastParagraph = new Paragraph(); /* * information table */ PdfPTable infoTable = new PdfPTable(3); infoTable.setWidthPercentage(100); infoTable.setWidths(new int[] {159, 65, 32}); // info that the user chose Paragraph chosenInfo = new Paragraph(); chosenInfo.add(new Phrase(language.get("please") + " ", TR_10)); chosenInfo.add(new Phrase(DOC.getFullNumber(), TR_10_B)); chosenInfo.add(Chunk.NEWLINE); chosenInfo.add(new Phrase(language.get("overdueCharge"), TR_10_B_I)); chosenInfo.add(Chunk.NEWLINE); chosenInfo.add(new Phrase(language.get("belongToSeller"), TR_10)); chosenInfo.add(Chunk.NEWLINE); chosenInfo.add(Chunk.NEWLINE); Paragraph subInfo = new Paragraph(new Phrase(language.get("thanksDueDate"), TR_10_B)); subInfo.setAlignment(Chunk.ALIGN_CENTER); chosenInfo.add(subInfo); PdfPCell chosenInfoCell = new PdfPCell(chosenInfo); chosenInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE); infoTable.addCell(chosenInfoCell); // all the sums Paragraph languageSumParagraph = new Paragraph(); /* * add language */ Phrase languageSum = new Phrase(language.get("sumEuro") + " :", TR_10); languageSumParagraph.add(languageSum); languageSumParagraph.add(Chunk.NEWLINE); Phrase languageVAT = new Phrase(language.get("vat") + " :", TR_10); languageSumParagraph.add(languageVAT); languageSumParagraph.add(Chunk.NEWLINE); Phrase languageTotal = new Phrase(language.get("totalEuro") + " :", TR_10); languageSumParagraph.add(languageTotal); languageSumParagraph.add(Chunk.NEWLINE); Phrase languageAdvance = new Phrase(language.get("advance") + " :", TR_10); languageSumParagraph.add(languageAdvance); languageSumParagraph.add(Chunk.NEWLINE); Phrase languageFinal = new Phrase(language.get("totalPay") + " :", TR_10_B); languageSumParagraph.add(languageFinal); // add the paragraph to table PdfPCell totalSumCell = new PdfPCell(languageSumParagraph); totalSumCell.setUseVariableBorders(true); totalSumCell.setBorderColorRight(BaseColor.WHITE); totalSumCell.setHorizontalAlignment(Element.ALIGN_RIGHT); infoTable.addCell(totalSumCell); /* * all the numbers */ Paragraph numbersParagraph = new Paragraph(); // total sum numbersParagraph.add(new Phrase(COMMA_2.format(totalSum), TR_10)); numbersParagraph.add(Chunk.NEWLINE); // VAT 20% double VAT = totalSum * 0.2; numbersParagraph.add(new Phrase(COMMA_2.format(VAT), TR_10)); numbersParagraph.add(Chunk.NEWLINE); // subsum with total+VAT double subSum = totalSum + VAT; numbersParagraph.add(new Phrase("" + COMMA_2.format(subSum), TR_10)); numbersParagraph.add(Chunk.NEWLINE); // advance numbersParagraph.add(new Phrase("-" + COMMA_2.format(DOC.getAdvance()), TR_10)); numbersParagraph.add(Chunk.NEWLINE); // final sum double finalSum = subSum - DOC.getAdvance(); numbersParagraph.add(new Phrase(COMMA_2.format(finalSum), TR_10_B)); // add the paragraph to table PdfPCell numbersCell = new PdfPCell(numbersParagraph); numbersCell.setUseVariableBorders(true); numbersCell.setBorderColorLeft(BaseColor.WHITE); numbersCell.setHorizontalAlignment(Element.ALIGN_RIGHT); infoTable.addCell(numbersCell); // add the info table to document lastParagraph.add(infoTable); int pageNumberAfterProducts = writer.getPageNumber(); /* * document creator and receiver info fields */ PdfPTable signaturesTable = new PdfPTable(2); signaturesTable.setWidthPercentage(100); signaturesTable.setWidths(new int[] {200, 200}); // creator Paragraph creatorParagraph = new Paragraph(); creatorParagraph.add(new Phrase(language.get("creator") + ":", TR_10)); creatorParagraph.add(Chunk.NEWLINE); creatorParagraph.add(new Phrase(user.getName() + ", " + user.getPhone(), TR_10)); PdfPCell creatorCell = new PdfPCell(creatorParagraph); creatorCell.setBorder(Rectangle.NO_BORDER); signaturesTable.addCell(creatorCell); // receiver Paragraph receiverParagraph = new Paragraph(); receiverParagraph.add(new Phrase(language.get("receiver") + ":", TR_10)); PdfPCell receiverCell = new PdfPCell(receiverParagraph); receiverCell.setBorder(Rectangle.NO_BORDER); signaturesTable.addCell(receiverCell); // add them to the table lastParagraph.add(signaturesTable); /* * finally add all the info to the document */ blackBoard.add(lastParagraph); try { blackBoard.close(); } catch (Exception x) { } reader = new PdfReader(temporaryByteStream.toByteArray()); try { temporaryByteStream.close(); } catch (Exception x) { } // close right after done for memory release int pageNumberAfterFinalEnd = reader.getNumberOfPages(); /* * now we make the final and last document that is ready to be sent to user */ finalDocument = new com.itextpdf.text.Document(); byteOutputStream = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(finalDocument, byteOutputStream); pageEvent.setPageCount(pageEvent.getPageCount(), true); writer.setPageEvent(pageEvent); finalDocument.open(); /* * check the last paragraph fit for our document */ if (pageNumberAfterFinalEnd > pageNumberAfterProducts) { // add the final paragraph to the new page finalDocument.add(firstParagraph); finalDocument.newPage(); finalDocument.add(emptyParagraph); finalDocument.add(lastParagraph); } else { finalDocument.add(firstParagraph); if (DOC.getProducts().size() == 0) { // we have no products, just to make it look nicer, add a blank finalDocument.add(emptyParagraph); } finalDocument.add(lastParagraph); } } catch (Exception x) { x.printStackTrace(); wasError = true; } finally { try { temporaryByteStream.close(); } catch (Exception x) { } try { byteOutputStream.close(); } catch (Exception x) { } try { blackBoard.close(); } catch (Exception x) { } try { finalDocument.close(); } catch (Exception x) { } } if (wasError) { return null; } if (byteOutputStream == null) { return null; } return byteOutputStream.toByteArray(); }
public static void main(String[] args) { SearchClientServiceImpl client = new SearchClientServiceImpl(); try { PdfReader reader = new PdfReader("c:\\tools\\files\\rezolutie.pdf"); PdfReaderContentParser parser = new PdfReaderContentParser(reader); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); String it = strategy.getResultantText(); if (it != null && !it.trim().isEmpty()) { System.out.println(it); DocumentVersions doc = new DocumentVersions(); doc.setContent(it); doc.setTitle("Han7"); doc.setDescription("Descriere"); doc.setData(new Date()); ObjectMapper mapper = new ObjectMapper(); String val = mapper.writeValueAsString(doc); client .getClient() .prepareIndex("twitter", "tweet", String.valueOf(i++)) .setSource(val) .get(); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { client.getClient().close(); } }
private static void booklet(String input) throws Exception { String output = input.replace(".pdf", "-booklet.pdf"); PdfReader reader = new PdfReader(input); int n = reader.getNumberOfPages(); Rectangle pageSize = reader.getPageSize(1); System.out.println("Input page size: " + pageSize); Document doc = new Document(PageSize.A4.rotate(), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output)); doc.open(); splitLine(doc, writer); int[] pages = new int[(n + 3) / 4 * 4]; int x = 1, y = pages.length; for (int i = 0; i < pages.length; ) { pages[i++] = y--; pages[i++] = x++; pages[i++] = x++; pages[i++] = y--; } PdfContentByte cb = writer.getDirectContent(); float bottom = (doc.top() - pageSize.getHeight()) / 2 + kOffset; float left = doc.right() / 2 - (pageSize.getWidth() + kTextWidth) / 2 - kMargin; float right = doc.right() / 2 - (pageSize.getWidth() - kTextWidth) / 2 + kMargin; for (int i = 0; i < pages.length; ) { PdfImportedPage page = getPage(writer, reader, pages[i++]); if (page != null) cb.addTemplate(page, left, bottom); page = getPage(writer, reader, pages[i++]); if (page != null) cb.addTemplate(page, right, bottom); doc.newPage(); } doc.close(); }
public void getContents() throws IOException { fileContents = ""; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); fileContents += strategy.getResultantText(); } }
private static void merge(String output, Collection<Path> all) { try { Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream(output)); document.open(); PdfReader reader; int n; for (Path pathTemp : all) { if (pathTemp.toFile().getAbsolutePath().endsWith(".pdf")) { reader = new PdfReader(pathTemp.toFile().getAbsolutePath()); n = reader.getNumberOfPages(); for (int page = 0; page < n; ) { copy.addPage(copy.getImportedPage(reader, ++page)); } copy.freeReader(reader); reader.close(); } } document.close(); } catch (Exception e) { System.out.println(e); } }
// FIXME: Manage Exceptions private OutputStream marcarReporteProgramaRechazado(final Programa programa, InputStream src) throws IOException, DocumentException { PdfReader reader = null; reader = new PdfReader(src); int n = reader.getNumberOfPages(); ByteArrayOutputStream os = new ByteArrayOutputStream(); PdfStamper stamper = null; stamper = new PdfStamper(reader, os); // text watermark Font f = new Font(Font.FontFamily.HELVETICA, 65); Phrase p = new Phrase("RECHAZADO", f); // transparency PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0.3f); // properties PdfContentByte over; Rectangle pagesize; float x, y; // loop over every page for (int i = 1; i <= n; i++) { pagesize = reader.getPageSizeWithRotation(i); x = (pagesize.getLeft() + pagesize.getRight()) / 2; y = (pagesize.getTop() + pagesize.getBottom()) / 2; over = stamper.getOverContent(i); over.saveState(); over.setGState(gs1); ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 45); } stamper.close(); reader.close(); return os; }
/** @see com.lowagie.tools.AbstractTool#execute() */ public static void execute(String srcvalue, String destvalue, String rotvalue) { try { if (StringUtils.isBlank(srcvalue)) { throw new InstantiationException("You need to choose a sourcefile"); } File src = new File(srcvalue); if (StringUtils.isBlank(destvalue)) { throw new InstantiationException("You need to choose a destination file"); } File dest = new File(destvalue); if (StringUtils.isBlank(rotvalue)) { throw new InstantiationException("You need to choose a rotation"); } int rotation = Integer.parseInt(rotvalue); // we create a reader for a certain document PdfReader reader = new PdfReader(src.getAbsolutePath()); // we retrieve the total number of pages and the page size int total = reader.getNumberOfPages(); System.out.println("There are " + total + " pages in the original file."); PdfDictionary pageDict; int currentRotation; for (int p = 1; p <= total; p++) { currentRotation = reader.getPageRotation(p); pageDict = reader.getPageN(p); pageDict.put(PdfName.ROTATE, new PdfNumber(currentRotation + rotation)); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); } catch (Exception e) { e.printStackTrace(); } }
private static void concatPDFs(List<String> pdfs, OutputStream outputStream, String tempDiv) { ByteArrayOutputStream byteStream = null; Document document = new Document(); try { PdfCopy copy = new PdfCopy(document, outputStream); document.open(); for (String pdf : pdfs) { String fileLocation = tempDiv + pdf; InputStream templateIs = new FileInputStream(fileLocation); PdfReader reader = new PdfReader(templateIs); byteStream = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(reader, byteStream); stamper.setFreeTextFlattening(true); stamper.setFormFlattening(true); stamper.close(); PdfReader pdfReader = new PdfReader(byteStream.toByteArray()); for (int page = 0; page < pdfReader.getNumberOfPages(); ) { copy.addPage(copy.getImportedPage(pdfReader, ++page)); } pdfReader.close(); reader.close(); } document.close(); copy.close(); } catch (Exception e) { logger.error(e, e); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (IOException ioe) { logger.error(ioe, ioe); } } }
/** * Parses a PDF and extracts all the images. * * @param src the source PDF * @param dest the resulting PDF */ public void extractImages(String filename) throws IOException, DocumentException { PdfReader reader = new PdfReader(filename); PdfReaderContentParser parser = new PdfReaderContentParser(reader); MyImageRenderListener listener = new MyImageRenderListener(RESULT); for (int i = 1; i <= reader.getNumberOfPages(); i++) { parser.processContent(i, listener); } }
public static ByteArrayOutputStream requestsToPdf( String globalTitle, Date generationDate, ScrambleRequest[] scrambleRequests, String password) throws DocumentException, IOException { Document doc = new Document(); ByteArrayOutputStream totalPdfOutput = new ByteArrayOutputStream(); PdfSmartCopy totalPdfWriter = new PdfSmartCopy(doc, totalPdfOutput); if (password != null) { totalPdfWriter.setEncryption( password.getBytes(), password.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); } doc.open(); PdfContentByte cb = totalPdfWriter.getDirectContent(); PdfOutline root = cb.getRootOutline(); HashMap<String, PdfOutline> outlineByPuzzle = new HashMap<String, PdfOutline>(); boolean expandPuzzleLinks = false; int pages = 1; for (int i = 0; i < scrambleRequests.length; i++) { ScrambleRequest scrambleRequest = scrambleRequests[i]; String shortName = scrambleRequest.scrambler.getShortName(); PdfOutline puzzleLink = outlineByPuzzle.get(shortName); if (puzzleLink == null) { PdfDestination d = new PdfDestination(PdfDestination.FIT); puzzleLink = new PdfOutline( root, PdfAction.gotoLocalPage(pages, d, totalPdfWriter), scrambleRequest.scrambler.getLongName(), expandPuzzleLinks); outlineByPuzzle.put(shortName, puzzleLink); } PdfDestination d = new PdfDestination(PdfDestination.FIT); new PdfOutline( puzzleLink, PdfAction.gotoLocalPage(pages, d, totalPdfWriter), scrambleRequest.title); PdfReader pdfReader = createPdf(globalTitle, generationDate, scrambleRequest); for (int j = 0; j < scrambleRequest.copies; j++) { for (int pageN = 1; pageN <= pdfReader.getNumberOfPages(); pageN++) { PdfImportedPage page = totalPdfWriter.getImportedPage(pdfReader, pageN); totalPdfWriter.addPage(page); pages++; } } } doc.close(); return totalPdfOutput; }
public static int getPageCount(File pdf) throws IOException { PdfReader reader = new PdfReader(pdf.getAbsolutePath()); try { return reader.getNumberOfPages(); } finally { if (reader != null) { reader.close(); } } }
/** * Parses a PDF to a plain text file. * * @param pdf the original PDF * @param txt the resulting text * @throws IOException */ public void parsePdf(String pdf, String txt) throws IOException { PdfReader reader = new PdfReader(pdf); PdfReaderContentParser parser = new PdfReaderContentParser(reader); PrintWriter out = new PrintWriter(new FileOutputStream(txt)); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); out.println(strategy.getResultantText()); } out.flush(); out.close(); }
/** * Parses a specific area of a PDF to a plain text file. * * @param pdf the original PDF * @param txt the resulting text * @throws IOException */ public void parsePdf(String pdf, String txt) throws IOException { PdfReader reader = new PdfReader(pdf); PrintWriter out = new PrintWriter(new FileOutputStream(txt)); Rectangle rect = new Rectangle(70, 80, 490, 580); RenderFilter filter = new RegionTextRenderFilter(rect); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter); out.println(PdfTextExtractor.getTextFromPage(reader, i, strategy)); } out.flush(); out.close(); }
public List<Contacts> readContacts(ContactsInitializer contactsInitializer) { Properties properties; String pdfinput; String contents; String[] content; String[] contact; int no_of_pages; int page_no = ApplicationConstants.TWO; PdfReader reader = null; try { properties = contactsInitializer.getProperties(); pdfinput = properties.getProperty(ApplicationConstants.PDF_INPUT); reader = new PdfReader(pdfinput); contents = PdfTextExtractor.getTextFromPage(reader, ApplicationConstants.ONE); content = contents.split(ApplicationConstants.NEW_LINE, ApplicationConstants.TWO); contact = content[1].split(ApplicationConstants.NEW_LINE); genarateContacts(contact); no_of_pages = reader.getNumberOfPages(); while (page_no <= no_of_pages) { contents = PdfTextExtractor.getTextFromPage(reader, page_no); contact = contents.split(ApplicationConstants.NEW_LINE); genarateContacts(contact); page_no++; } logger.info(list.size() + " contacts added to list from pdf file successfully !"); System.out.println(list.size() + " contacts added to list from pdf file successfully !"); } catch (Exception exception) { System.out.println("contacts not created !"); logger.error("contacts not created !"); logger.error(exception); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); logger.debug(LoggerConstants.RESOURCES_RELEASED); } catch (Exception exception) { logger.error(exception); exception.printStackTrace(); } } } return list; }
private void readFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); PdfReader reader = new PdfReader(inputStream); int numberOfPages = reader.getNumberOfPages(); for (int page = 1; page <= numberOfPages; page++) { String pageContent = PdfTextExtractor.getTextFromPage(reader, page); List<String> lines = new ArrayList<>(Arrays.asList(pageContent.split("\n"))); for (String line : lines) { if (line.matches("^\\d{2}\\.\\d{2}\\.\\d{4}.+")) { parseLine(line); } } } }
private File convertPdfToPdfA(final InputStream source) throws IOException, DocumentException { final File pdfAFile = TempFileProvider.createTempFile("digitalSigning-" + System.currentTimeMillis(), ".pdf"); // Reads a PDF document. PdfReader reader = new PdfReader(source); // PdfStamper: Applies extra content to the pages of a PDF document. This extra content can be // all the objects allowed in // PdfContentByte including pages from other Pdfs. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfAFile)); // A generic Document class. Document document = new Document(); // we create a writer that listens to the document PdfWriter writer = stamper.getWriter(); int numberPages = reader.getNumberOfPages(); writer.setPDFXConformance(PdfWriter.PDFA1A); document.open(); // PdfDictionary:A dictionary is an associative table containing pairs of objects. // The first element of each pair is called the key and the second element is called the value // <CODE>PdfName</CODE> is an object that can be used as a name in a PDF-file PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT); outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.S, PdfName.GTS_PDFA1); writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(outi)); // Add pages PdfImportedPage p = null; Image image; for (int i = 0; i < numberPages; i++) { p = writer.getImportedPage(reader, i + 1); image = Image.getInstance(p); document.add(image); } writer.createXmpMetadata(); document.close(); // Add Metadata from source pdf HashMap<String, String> info = reader.getInfo(); stamper.setMoreInfo(info); stamper.close(); return pdfAFile; }
private static void crop(String input) throws Exception { String output = input.replace(".pdf", "-crop.pdf"); PdfReader reader = new PdfReader(input); final int n = reader.getNumberOfPages(); Rectangle pageSize = reader.getPageSize(1); System.out.println("Input page size: " + pageSize); float left = (pageSize.getWidth() - kTextWidth) / 2 - kMargin; float right = pageSize.getWidth() - left; float bottom = (pageSize.getHeight() - kTextHeight) / 2; float top = pageSize.getHeight() - bottom; PdfRectangle rect = new PdfRectangle(left, bottom + kOffset, right, top + kOffset); for (int i = 1; i <= n; i++) { PdfDictionary pageDict = reader.getPageN(i); pageDict.put(PdfName.CROPBOX, rect); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output)); stamper.close(); }
public static void main(String[] args) { try { // Read file using PdfReader PdfReader pdfReader = new PdfReader("HelloWorld.pdf"); // Modify file using PdfReader PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-modified.pdf")); Image image = Image.getInstance("temp.png"); image.scaleAbsolute(100, 50); image.setAbsolutePosition(100f, 700f); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getUnderContent(i); content.addImage(image); } pdfStamper.close(); } catch (IOException | DocumentException e) { logger.warn("failed to ...." + e); } }
/** * Given an iText PDF Reader, extract image data from the PDF and store it in a XOM XML element. * * @param reader A reader for the given PDF. * @return A XOM element containing image data. */ public static Element extractToXML(PdfReader reader) { Element root = new Element("Images"); PdfReaderContentParser parser = new PdfReaderContentParser(reader); // Go through the PDF one page at a time, pulling images from each page. ImageRenderListener listener = new ImageRenderListener(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { try { listener = parser.processContent(i, new ImageRenderListener()); } catch (IOException e) { } List<Element> images = listener.getImageData(); // Add the current page number to each image, add it to the root. if (images != null) { for (Element image : images) { image.addAttribute(new Attribute("Page", Integer.toString(i))); root.appendChild(image); } } } return root; }
/** * 「比較」イベントです。 * * @param e イベント情報 * @throws Exception 処理例外 */ protected void compareActionPerformed(ActionEvent e) throws Exception { // 比較 if (!new File(getPdf1().getText()).exists()) { ACMessageBox.showExclamation("PDF1が見つかりません。"); return; } if (!new File(getPdf2().getText()).exists()) { ACMessageBox.showExclamation("PDF2が見つかりません。"); return; } final PdfReader p1 = new PdfReader(getPdf1().getText()); final PdfReader p2 = new PdfReader(getPdf2().getText()); final int pages1 = p1.getNumberOfPages(); final int pages2 = p2.getNumberOfPages(); if (pages1 != pages2) { if (pages1 > pages2) { ACMessageBox.showExclamation("PDF1よりもPDF2のページ数が少ないです。"); return; } if (ACMessageBox.showOkCancel( "PDFのページ数が異なります。" + ACConstants.LINE_SEPARATOR + "PDF1のすべてのページがPDF2に含まれるかで比較しますか?") != ACMessageBox.RESULT_OK) { return; } } new Runnable() { private boolean firstLock; public void run() { final int stopKeyCode = KeyEvent.VK_CAPS_LOCK; firstLock = Toolkit.getDefaultToolkit().getLockingKeyState(stopKeyCode); LinkedList<Integer> pages = new LinkedList<Integer>(); for (int i = 1; i <= pages2; i++) { pages.add(new Integer(i)); } errorCount = 0; pageOfProcessed = 0; pageOfCount = pages1; StringBuilder sb = new StringBuilder(); for (int i = 1; i <= pages1; i++) { try { boolean match = false; byte[] b1 = p1.getPageContent(i); Iterator<Integer> it = pages.iterator(); while (it.hasNext()) { int page = ((Integer) it.next()).intValue(); byte[] b2 = p2.getPageContent(page); if (Arrays.equals(b1, b2)) { sb.append("○PDF1(" + i + ") = PDF2(" + page + ")" + ACConstants.LINE_SEPARATOR); match = true; it.remove(); break; } } if (!match) { sb.append("×PDF1(" + i + ") 【一致なし】" + ACConstants.LINE_SEPARATOR); errorCount++; } } catch (Exception ex) { sb.append("※PDF1(" + i + ") 【処理例外】" + ACConstants.LINE_SEPARATOR); errorCount++; } setProgress(sb); pageOfProcessed = i; if (Toolkit.getDefaultToolkit().getLockingKeyState(stopKeyCode) != firstLock) { getResult() .setText( "!比較中断(" + pageOfProcessed + " / " + pageOfCount + ") / 不一致数:" + errorCount + " 件" + ACConstants.LINE_SEPARATOR + sb.toString()); return; } } getResult() .setText( "■比較完了(" + pageOfProcessed + " / " + pageOfCount + ") / 不一致数:" + errorCount + " 件" + ACConstants.LINE_SEPARATOR + sb.toString()); } }.run(); }
private static PdfReader createPdf( String globalTitle, Date creationDate, ScrambleRequest scrambleRequest) throws DocumentException, IOException { azzert(scrambleRequest.scrambles.length > 0); ByteArrayOutputStream pdfOut = new ByteArrayOutputStream(); Rectangle pageSize = PageSize.LETTER; Document doc = new Document(pageSize, 0, 0, 75, 75); PdfWriter docWriter = PdfWriter.getInstance(doc, pdfOut); docWriter.setBoxSize( "art", new Rectangle(36, 54, pageSize.getWidth() - 36, pageSize.getHeight() - 54)); doc.addCreationDate(); doc.addProducer(); if (globalTitle != null) { doc.addTitle(globalTitle); } doc.open(); // Note that we ignore scrambleRequest.copies here. addScrambles(docWriter, doc, scrambleRequest, globalTitle); doc.close(); // TODO - is there a better way to convert from a PdfWriter to a PdfReader? PdfReader pr = new PdfReader(pdfOut.toByteArray()); if (scrambleRequest.fmc) { // We don't watermark the FMC sheets because they already have // the competition name on them. return pr; } pdfOut = new ByteArrayOutputStream(); doc = new Document(pageSize, 0, 0, 75, 75); docWriter = PdfWriter.getInstance(doc, pdfOut); doc.open(); PdfContentByte cb = docWriter.getDirectContent(); for (int pageN = 1; pageN <= pr.getNumberOfPages(); pageN++) { PdfImportedPage page = docWriter.getImportedPage(pr, pageN); doc.newPage(); cb.addTemplate(page, 0, 0); Rectangle rect = pr.getBoxSize(pageN, "art"); // Header ColumnText.showTextAligned( cb, Element.ALIGN_LEFT, new Phrase(Utils.SDF.format(creationDate)), rect.getLeft(), rect.getTop(), 0); ColumnText.showTextAligned( cb, Element.ALIGN_CENTER, new Phrase(globalTitle), (pageSize.getLeft() + pageSize.getRight()) / 2, pageSize.getTop() - 60, 0); ColumnText.showTextAligned( cb, Element.ALIGN_CENTER, new Phrase(scrambleRequest.title), (pageSize.getLeft() + pageSize.getRight()) / 2, pageSize.getTop() - 45, 0); if (pr.getNumberOfPages() > 1) { ColumnText.showTextAligned( cb, Element.ALIGN_RIGHT, new Phrase(pageN + "/" + pr.getNumberOfPages()), rect.getRight(), rect.getTop(), 0); } // Footer String generatedBy = "Generated by " + Utils.getProjectName() + "-" + Utils.getVersion(); ColumnText.showTextAligned( cb, Element.ALIGN_CENTER, new Phrase(generatedBy), (pageSize.getLeft() + pageSize.getRight()) / 2, pageSize.getBottom() + 40, 0); } doc.close(); // TODO - is there a better way to convert from a PdfWriter to a PdfReader? pr = new PdfReader(pdfOut.toByteArray()); return pr; // The PdfStamper class doesn't seem to be working. // pdfOut = new ByteArrayOutputStream(); // PdfStamper ps = new PdfStamper(pr, pdfOut); // // for(int pageN = 1; pageN <= pr.getNumberOfPages(); pageN++) { // PdfContentByte pb = ps.getUnderContent(pageN); // Rectangle rect = pr.getBoxSize(pageN, "art"); // System.out.println(rect.getLeft()); // System.out.println(rect.getWidth()); // ColumnText.showTextAligned(pb, // Element.ALIGN_LEFT, new Phrase("Hello people!"), 36, 540, 0); //// ColumnText.showTextAligned(pb, //// Element.ALIGN_CENTER, new Phrase("HELLO WORLD"), //// (rect.getLeft() + rect.getRight()) / 2, rect.getTop(), 0); // } // ps.close(); // return ps.getReader(); }
private static PdfImportedPage getPage(PdfWriter writer, PdfReader reader, int page) { if (page > 0 && page <= reader.getNumberOfPages()) return writer.getImportedPage(reader, page); else return null; }
private AlfrescoRuntimeException signFile( final NodeRef nodeRefToSign, final DigitalSigningDTO signingDTO, final File alfTempDir, final String alias, final KeyStore ks, final PrivateKey key, final Certificate[] chain) { final String fileNameToSign = fileFolderService.getFileInfo(nodeRefToSign).getName(); File fileConverted = null; File tempDir = null; try { ContentReader fileToSignContentReader = getReader(nodeRefToSign); if (fileToSignContentReader != null) { String newName = null; // Check if document is PDF or transform it if (!MimetypeMap.MIMETYPE_PDF.equals(fileToSignContentReader.getMimetype())) { // Transform document in PDF document final ContentTransformer tranformer = contentTransformerRegistry.getTransformer( fileToSignContentReader.getMimetype(), fileToSignContentReader.getSize(), MimetypeMap.MIMETYPE_PDF, new TransformationOptions()); if (tranformer != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); fileConverted = new File(tempDir, fileNameToSign + "_" + System.currentTimeMillis() + ".pdf"); if (fileConverted != null) { final ContentWriter newDoc = new FileContentWriter(fileConverted); if (newDoc != null) { newDoc.setMimetype(MimetypeMap.MIMETYPE_PDF); tranformer.transform(fileToSignContentReader, newDoc); fileToSignContentReader = new FileContentReader(fileConverted); final String originalName = (String) nodeService.getProperty(nodeRefToSign, ContentModel.PROP_NAME); newName = originalName.substring(0, originalName.lastIndexOf(".")) + ".pdf"; } } } } else { log.error( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); } } // Convert PDF in PDF/A format final File pdfAFile = convertPdfToPdfA(fileToSignContentReader.getContentInputStream()); final PdfReader reader = new PdfReader(new FileInputStream(pdfAFile)); if (nodeRefToSign != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); final File file = new File(tempDir, fileNameToSign); if (file != null) { final FileOutputStream fout = new FileOutputStream(file); final PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); if (stp != null) { final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (sap != null) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason(signingDTO.getSignReason()); sap.setLocation(signingDTO.getSignLocation()); sap.setContact(signingDTO.getSignContact()); sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); sap.setImageScale(1); // digital signature if (signingDTO.getSigningField() != null && !signingDTO.getSigningField().trim().equalsIgnoreCase("")) { Image img = null; if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); final AcroFields af = reader.getAcroFields(); if (af != null) { final List<FieldPosition> positions = af.getFieldPositions(signingDTO.getSigningField()); if (positions != null && positions.size() > 0 && positions.get(0) != null && positions.get(0).position != null) { final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, Float.valueOf(positions.get(0).position.getWidth()).intValue(), Float.valueOf(positions.get(0).position.getHeight()).intValue()); img = Image.getInstance(newImg, null); } else { log.error( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); } } if (img == null) { img = Image.getInstance( ImageIO.read(imageContentReader.getContentInputStream()), null); } sap.setImage(img); } sap.setVisibleSignature(signingDTO.getSigningField()); } else { int pageToSign = 1; if (DigitalSigningDTO.PAGE_LAST.equalsIgnoreCase( signingDTO.getPages().trim())) { pageToSign = reader.getNumberOfPages(); } else if (DigitalSigningDTO.PAGE_SPECIFIC.equalsIgnoreCase( signingDTO.getPages().trim())) { if (signingDTO.getPageNumber() > 0 && signingDTO.getPageNumber() <= reader.getNumberOfPages()) { pageToSign = signingDTO.getPageNumber(); } else { throw new AlfrescoRuntimeException("Page number is out of bound."); } } if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); // Resize image final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, signingDTO.getSignWidth(), signingDTO.getSignHeight()); final Image img = Image.getInstance(newImg, null); sap.setImage(img); } if (signingDTO.getPosition() != null && !DigitalSigningDTO.POSITION_CUSTOM.equalsIgnoreCase( signingDTO.getPosition().trim())) { final Rectangle pageRect = reader.getPageSizeWithRotation(1); sap.setVisibleSignature( positionSignature( signingDTO.getPosition(), pageRect, signingDTO.getSignWidth(), signingDTO.getSignHeight(), signingDTO.getxMargin(), signingDTO.getyMargin()), pageToSign, null); } else { sap.setVisibleSignature( new Rectangle( signingDTO.getLocationX(), signingDTO.getLocationY(), signingDTO.getLocationX() + signingDTO.getSignWidth(), signingDTO.getLocationY() - signingDTO.getSignHeight()), pageToSign, null); } } stp.close(); NodeRef destinationNode = null; NodeRef originalDoc = null; boolean addAsNewVersion = false; if (signingDTO.getDestinationFolder() == null) { destinationNode = nodeRefToSign; nodeService.addAspect(destinationNode, ContentModel.ASPECT_VERSIONABLE, null); addAsNewVersion = true; } else { originalDoc = nodeRefToSign; destinationNode = createDestinationNode( file.getName(), signingDTO.getDestinationFolder(), nodeRefToSign); } if (destinationNode != null) { final ContentWriter writer = contentService.getWriter(destinationNode, ContentModel.PROP_CONTENT, true); if (writer != null) { writer.setEncoding(fileToSignContentReader.getEncoding()); writer.setMimetype("application/pdf"); writer.putContent(file); file.delete(); if (fileConverted != null) { fileConverted.delete(); } nodeService.addAspect( destinationNode, SigningModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); nodeService.setProperty( destinationNode, SigningModel.PROP_REASON, signingDTO.getSignReason()); nodeService.setProperty( destinationNode, SigningModel.PROP_LOCATION, signingDTO.getSignLocation()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNATUREDATE, new java.util.Date()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); if (newName != null) { nodeService.setProperty(destinationNode, ContentModel.PROP_NAME, newName); } final X509Certificate c = (X509Certificate) ks.getCertificate(alias); nodeService.setProperty( destinationNode, SigningModel.PROP_VALIDITY, c.getNotAfter()); nodeService.setProperty( destinationNode, SigningModel.PROP_ORIGINAL_DOC, originalDoc); if (!addAsNewVersion) { if (!nodeService.hasAspect(originalDoc, SigningModel.ASPECT_ORIGINAL_DOC)) { nodeService.addAspect( originalDoc, SigningModel.ASPECT_ORIGINAL_DOC, new HashMap<QName, Serializable>()); } nodeService.createAssociation( originalDoc, destinationNode, SigningModel.PROP_RELATED_DOC); } } } else { log.error("[" + fileNameToSign + "] Destination node is not a valid NodeRef."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Destination node is not a valid NodeRef."); } } else { log.error("[" + fileNameToSign + "] Unable to get PDF appearance signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get PDF appearance signature."); } } else { log.error("[" + fileNameToSign + "] Unable to create PDF signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to create PDF signature."); } } } } else { log.error("[" + fileNameToSign + "] Unable to get document to sign content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get document to sign content."); } if (pdfAFile != null) { pdfAFile.delete(); } return null; } else { log.error("[" + fileNameToSign + "] The document has no content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The document has no content."); } } catch (KeyStoreException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (ContentIOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (IOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (DocumentException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { log.error("[" + fileNameToSign + "] " + ex); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + ex.getMessage(), ex); } } } }
public byte[] make(Firm firm, User user) { /* * make metadata for the document */ Language language = DOC.getLanguage(); GregorianCalendar gregCalendar = new GregorianCalendar(); gregCalendar.setTime(DOC.getDate()); SimpleDateFormat sdf = DateFormats.DOT_DATE_FORMAT(); DecimalFormat COMMA_3 = NumberFormats.THREE_AFTER_COMMA(); DecimalFormat COMMA_2 = NumberFormats.TWO_AFTER_COMMA(); DecimalFormat DISCOUNT = NumberFormats.DISCOUNT_FORMAT(); Font TR_12_B = DocumentFonts.TIMES_ROMAN_12_BOLD(); Font TR_12 = DocumentFonts.TIMES_ROMAN_12(); Font TR_10_B = DocumentFonts.TIMES_ROMAN_10_BOLD(); Font TR_10 = DocumentFonts.TIMES_ROMAN_10(); Font TR_10_I = DocumentFonts.TIMES_ROMAN_10_ITALIC(); Font TR_10_U_B = DocumentFonts.TIMES_ROMAN_10_UNDERLINE_BOLD(); Font TR_8_I = DocumentFonts.TIMES_ROMAN_8_ITALIC(); com.itextpdf.text.Document blackBoard = null; com.itextpdf.text.Document finalDocument = null; ByteArrayOutputStream byteOutputStream = null; ByteArrayOutputStream temporaryByteStream = null; PdfReader reader; HeaderFooter pageEvent = new HeaderFooter(firm, true, true); boolean wasError = false; /* * make the document */ try { // make an empty cell and paragraph, going to need them later multiple times PdfPCell emptyCell = new PdfPCell(new Phrase(" ")); emptyCell.setBorder(Rectangle.NO_BORDER); Paragraph emptyParagraph = new Paragraph(" "); /* * First paragraph of the page, included in every page afterwards */ Paragraph pageStartParagraph = new Paragraph(); PdfPTable headerTable = new PdfPTable(2); // table with 2 columns headerTable.setWidths(new int[] {170, 300}); // table column sizes headerTable.setWidthPercentage(100); // Type cell headerTable.addCell( new PdfPCell( new Phrase( language.get("orderConfirmation") + ": " + DOC.getFullNumber(), TR_12_B))); // language client PdfPCell languageClient = new PdfPCell(new Phrase(language.get("capitalClient") + " :", TR_10_U_B)); languageClient.setHorizontalAlignment(Element.ALIGN_RIGHT); languageClient.setBorder(Rectangle.NO_BORDER); headerTable.addCell(languageClient); pageStartParagraph.add(headerTable); // CE mark if (DOC.isShowCE()) { PdfPTable CETable = new PdfPTable(2); CETable.setWidthPercentage(100); CETable.setWidths(new int[] {25, 445}); // CE image Image ce = null; try { ce = Image.getInstance(getClass().getResource("/images/ce.png")); ce.scaleToFit(24, 24); ce.setAlignment(Element.ALIGN_CENTER); } catch (Exception e) { } PdfPCell ceCell = new PdfPCell(ce); ceCell.setBorder(Rectangle.NO_BORDER); CETable.addCell(ceCell); // CE description PdfPCell CEspecCell = new PdfPCell(new Phrase(DOC.getCeSpecification(), TR_10)); CEspecCell.setBorder(Rectangle.NO_BORDER); CETable.addCell(CEspecCell); pageStartParagraph.add(CETable); } PdfPTable headerTableSecond = new PdfPTable(2); // table with 2 columns headerTableSecond.setWidths(new int[] {170, 300}); // table column sizes headerTableSecond.setWidthPercentage(100); // Date cell PdfPCell dateCell = new PdfPCell(new Phrase(DOC.getFormatedDate(), TR_10)); dateCell.setHorizontalAlignment(Element.ALIGN_RIGHT); dateCell.setBorder(Rectangle.NO_BORDER); headerTableSecond.addCell(dateCell); // client name cell String fullClientName; if (DOC.getClient().getSelectedContactPerson().getID() == 0) { // contact person not selected fullClientName = DOC.getClient().getName(); } else { fullClientName = DOC.getClient().getName() + ", " + DOC.getClient().getSelectedContactPerson().getName(); } PdfPCell clientNameCell = new PdfPCell(new Phrase(fullClientName, TR_10_B)); clientNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT); clientNameCell.setBorder(Rectangle.NO_BORDER); headerTableSecond.addCell(clientNameCell); // empty cell headerTableSecond.addCell(emptyCell); // client phone cell PdfPCell clientPhoneCell = new PdfPCell(new Phrase(DOC.getClient().getPhone(), TR_10_I)); clientPhoneCell.setHorizontalAlignment(Element.ALIGN_RIGHT); clientPhoneCell.setBorder(Rectangle.NO_BORDER); headerTableSecond.addCell(clientPhoneCell); // empty cell headerTableSecond.addCell(emptyCell); // client email cell PdfPCell clientEmailCell = new PdfPCell(new Phrase(DOC.getClient().getEmail(), TR_10_I)); clientEmailCell.setHorizontalAlignment(Element.ALIGN_RIGHT); clientEmailCell.setBorder(Rectangle.NO_BORDER); headerTableSecond.addCell(clientEmailCell); // done with second header table pageStartParagraph.add(headerTableSecond); /* * Let's make a copy for later page checking */ blackBoard = new com.itextpdf.text.Document(); temporaryByteStream = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(blackBoard, temporaryByteStream); pageEvent.setPageStartParagraph(pageStartParagraph); writer.setPageEvent(pageEvent); blackBoard.open(); /* * First paragraph */ Paragraph firstParagraph = new Paragraph(); // thank the customer firstParagraph.add(new Phrase(language.get("thanksForBuying"), TR_10_I)); /* * Products header table */ PdfPTable productsHeaderRow; int[] productsTableWidths; if (DOC.isShowDiscount()) { productsHeaderRow = new PdfPTable(7); productsTableWidths = new int[] {8, 93, 17, 12, 20, 15, 25}; } else { productsHeaderRow = new PdfPTable(6); productsTableWidths = new int[] {8, 110, 17, 12, 20, 23}; } productsHeaderRow.setWidthPercentage(100); productsHeaderRow.setWidths(productsTableWidths); // products table header row PdfPCell headerNRCell = new PdfPCell(new Phrase(language.get("nr"), TR_12)); headerNRCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerNRCell); productsHeaderRow.addCell(new PdfPCell(new Phrase(language.get("specification"), TR_12))); PdfPCell headerAmountCell = new PdfPCell(new Phrase(language.get("amount"), TR_12)); headerAmountCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerAmountCell); PdfPCell headerUnitCell = new PdfPCell(new Phrase(language.get("unit"), TR_12)); headerUnitCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerUnitCell); PdfPCell headerPriceCell = new PdfPCell(new Phrase(language.get("price"), TR_12)); headerPriceCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerPriceCell); if (DOC.isShowDiscount()) { PdfPCell headerDiscountCell = new PdfPCell(new Phrase(language.get("discount"), TR_12)); headerDiscountCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerDiscountCell); } PdfPCell headerSumCell = new PdfPCell(new Phrase(language.get("sum"), TR_12)); headerSumCell.setHorizontalAlignment(Element.ALIGN_CENTER); productsHeaderRow.addCell(headerSumCell); // add all the products double totalSum = 0; int lastPageNumber = 0; boolean firstProductInPage = true; boolean updateBlackBoard = false; for (int i = 0; i < DOC.getProducts().size(); i++) { Product product = DOC.getProducts().get(i); // check the language and make string accordingly String productName = "", productUnit = ""; if (language.getType().equals(Language.TYPE_ESTONIAN)) { productName = product.getName(); productUnit = product.getUnit(); } else if (language.getType().equals(Language.TYPE_ENGLISH)) { productName = product.getE_name(); productUnit = product.getE_unit(); } // each products has a separate table with the same size as header PdfPTable productRow = new PdfPTable(productsHeaderRow.getNumberOfColumns()); productRow.setWidthPercentage(100); productRow.setWidths(productsTableWidths); PdfPCell NRCEll = new PdfPCell(new Phrase("" + (i + 1), TR_10)); NRCEll.setHorizontalAlignment(Element.ALIGN_CENTER); NRCEll.setBorderColor(BaseColor.LIGHT_GRAY); // name cell with additional info PdfPCell nameCell = null; if (product .hasAdditionalInformation()) { // user has added additional information for this product Paragraph nameAndInfoParagraph = new Paragraph(); nameAndInfoParagraph.add(new Phrase(productName, TR_10)); nameAndInfoParagraph.add(Chunk.NEWLINE); nameAndInfoParagraph.add(new Phrase(product.getAdditional_Info(), TR_8_I)); nameCell = new PdfPCell(new Phrase(nameAndInfoParagraph)); } else { nameCell = new PdfPCell(new Phrase(productName, TR_10)); } nameCell.setBorderColor(BaseColor.LIGHT_GRAY); // amount cell PdfPCell amountCell = new PdfPCell(new Phrase(product.getAmount() + "", TR_10)); amountCell.setHorizontalAlignment(Element.ALIGN_CENTER); amountCell.setBorderColor(BaseColor.LIGHT_GRAY); // unit cell PdfPCell unitCell = new PdfPCell(new Phrase(productUnit, TR_10)); unitCell.setHorizontalAlignment(Element.ALIGN_CENTER); unitCell.setBorderColor(BaseColor.LIGHT_GRAY); // price cell PdfPCell priceCell = new PdfPCell(new Phrase(COMMA_3.format(product.getPrice()), TR_10)); priceCell.setHorizontalAlignment(Element.ALIGN_CENTER); priceCell.setBorderColor(BaseColor.LIGHT_GRAY); // discount cell PdfPCell discountCell = null; if (DOC.isShowDiscount()) { discountCell = new PdfPCell(new Phrase(DISCOUNT.format(product.getDiscount()), TR_10)); discountCell.setHorizontalAlignment(Element.ALIGN_CENTER); discountCell.setBorderColor(BaseColor.LIGHT_GRAY); } // sum cell PdfPCell sumCell = new PdfPCell(new Phrase(COMMA_2.format(product.getTotalSum()), TR_10)); sumCell.setHorizontalAlignment(Element.ALIGN_RIGHT); sumCell.setBorderColor(BaseColor.LIGHT_GRAY); // add all the cells productRow.addCell(NRCEll); productRow.addCell(nameCell); productRow.addCell(amountCell); productRow.addCell(unitCell); productRow.addCell(priceCell); if (DOC.isShowDiscount()) { productRow.addCell(discountCell); } productRow.addCell(sumCell); // add the product row to the blackboard blackBoard.add(productRow); /* * check if we changed a page with the last product add, */ int currentPageNumber = writer.getPageNumber(); if (currentPageNumber > lastPageNumber) { blackBoard.add(productsHeaderRow); // add the table header again to the new page blackBoard.add(emptyParagraph); firstProductInPage = true; lastPageNumber++; } if (firstProductInPage) { // first product row needs to have black edges on top productRow.deleteLastRow(); // delete the last row and re-add later with changed color if (currentPageNumber > 1) { // eliminate the possibility of too-long additional info ending up half paged // on old page firstParagraph.add(new Chunk(Chunk.NEXTPAGE)); } firstParagraph.add(emptyParagraph); // empty space between the page header firstParagraph.add(productsHeaderRow); firstProductInPage = false; updateBlackBoard = true; float borderWidth = NRCEll.getBorderWidth(); NRCEll.setUseVariableBorders(true); nameCell.setUseVariableBorders(true); amountCell.setUseVariableBorders(true); unitCell.setUseVariableBorders(true); priceCell.setUseVariableBorders(true); if (DOC.isShowDiscount()) { discountCell.setUseVariableBorders(true); } sumCell.setUseVariableBorders(true); NRCEll.setBorderColorTop(BaseColor.BLACK); nameCell.setBorderColorTop(BaseColor.BLACK); amountCell.setBorderColorTop(BaseColor.BLACK); unitCell.setBorderColorTop(BaseColor.BLACK); priceCell.setBorderColorTop(BaseColor.BLACK); if (DOC.isShowDiscount()) { discountCell.setBorderColorTop(BaseColor.BLACK); } sumCell.setBorderColorTop(BaseColor.BLACK); /* * this is needed, because SOMEWHY color changing also changes the width */ NRCEll.setBorderWidth(borderWidth / 2); nameCell.setBorderWidth(borderWidth / 2); amountCell.setBorderWidth(borderWidth / 2); unitCell.setBorderWidth(borderWidth / 2); priceCell.setBorderWidth(borderWidth / 2); if (DOC.isShowDiscount()) { discountCell.setBorderWidth(borderWidth / 2); } sumCell.setBorderWidth(borderWidth / 2); productRow.addCell(NRCEll); productRow.addCell(nameCell); productRow.addCell(amountCell); productRow.addCell(unitCell); productRow.addCell(priceCell); if (DOC.isShowDiscount()) { productRow.addCell(discountCell); } productRow.addCell(sumCell); } totalSum += product.getTotalSum(); firstParagraph.add(productRow); /* * update the blackBoard, because we added another page to the document, update the page number */ if (updateBlackBoard) { blackBoard.close(); blackBoard = new com.itextpdf.text.Document(); try { temporaryByteStream.close(); } catch (Exception x) { } // close right after done for memory release temporaryByteStream = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(blackBoard, temporaryByteStream); pageEvent.resetPagesTotal(); writer.setPageEvent(pageEvent); blackBoard.open(); blackBoard.add(firstParagraph); updateBlackBoard = false; } } /* * last paragraph, includes page end information */ Paragraph lastParagraph = new Paragraph(); /* * information table */ PdfPTable infoTable = new PdfPTable(3); infoTable.setWidthPercentage(100); infoTable.setWidths(new int[] {159, 65, 32}); Paragraph infoParagraph = new Paragraph(); // valid due date String validDueDate = " "; if (DOC.getValidDue() != 0) { // user has set the validDue for the document validDueDate = language.get("dueDate") + " " + sdf.format( new Date( gregCalendar.getTimeInMillis() + (DOC.getValidDue() * 24 * 60 * 60 * 1000L))); } infoParagraph.add(new Phrase(validDueDate, TR_10)); infoParagraph.add(Chunk.NEWLINE); // instructions for the buyer infoParagraph.add(new Phrase(language.get("please") + " ", TR_10)); infoParagraph.add(new Phrase(DOC.getFullNumber(), TR_10_B)); PdfPCell infoCell = new PdfPCell(infoParagraph); infoCell.setVerticalAlignment(Element.ALIGN_MIDDLE); infoTable.addCell(infoCell); // the money info Paragraph languageParagraph = new Paragraph(); // language sum languageParagraph.add(new Phrase(language.get("sumTotalEuro") + " :", TR_10)); languageParagraph.add(Chunk.NEWLINE); // language VAT languageParagraph.add(new Phrase(language.get("vat") + " :", TR_10)); languageParagraph.add(Chunk.NEWLINE); // language total languageParagraph.add(new Phrase(language.get("totalPay") + " :", TR_10_B)); PdfPCell languageCell = new PdfPCell(languageParagraph); languageCell.setUseVariableBorders(true); languageCell.setBorderColorRight(BaseColor.WHITE); languageCell.setHorizontalAlignment(Element.ALIGN_RIGHT); infoTable.addCell(languageCell); // numbers paragraph Paragraph numbersParagaph = new Paragraph(); // sum numbersParagaph.add(new Phrase("" + COMMA_2.format(totalSum), TR_10)); numbersParagaph.add(Chunk.NEWLINE); // VAT 20% numbersParagaph.add(new Phrase("" + COMMA_2.format(totalSum * 0.2), TR_10)); numbersParagaph.add(Chunk.NEWLINE); // total numbersParagaph.add(new Phrase("" + COMMA_2.format(totalSum + (totalSum * 0.2)), TR_10_B)); PdfPCell numbersCell = new PdfPCell(numbersParagaph); numbersCell.setUseVariableBorders(true); numbersCell.setBorderColorLeft(BaseColor.WHITE); numbersCell.setHorizontalAlignment(Element.ALIGN_RIGHT); infoTable.addCell(numbersCell); lastParagraph.add(infoTable); int pageNumberAfterProducts = writer.getPageNumber(); /* * shipment data */ PdfPTable shipmentTable = new PdfPTable(2); shipmentTable.setWidthPercentage(100); shipmentTable.setWidths(new int[] {30, 140}); Paragraph shipLangParagraph = new Paragraph(); // time shipLangParagraph.add(new Phrase(language.get("shipmentTime") + ":", TR_10_B)); shipLangParagraph.add(Chunk.NEWLINE); // address shipLangParagraph.add(new Phrase(language.get("shipmentAddress") + ":", TR_10_B)); shipLangParagraph.add(Chunk.NEWLINE); // payment requirement shipLangParagraph.add(new Phrase(language.get("paymentRequirement") + ":", TR_10_B)); // add to the table PdfPCell shipLangCell = new PdfPCell(shipLangParagraph); shipLangCell.setBorder(Rectangle.NO_BORDER); shipmentTable.addCell(shipLangCell); // document shipment data Paragraph shipmentParagraph = new Paragraph(); // time shipmentParagraph.add(new Phrase(DOC.getShipmentTime(), TR_10)); shipmentParagraph.add(Chunk.NEWLINE); // place shipmentParagraph.add(new Phrase(DOC.getShipmentAddress(), TR_10)); shipmentParagraph.add(Chunk.NEWLINE); // address shipmentParagraph.add(new Phrase(DOC.getPaymentRequirement(), TR_10)); // add to the table PdfPCell shipmentCell = new PdfPCell(shipmentParagraph); shipmentCell.setBorder(Rectangle.NO_BORDER); shipmentTable.addCell(shipmentCell); lastParagraph.add(shipmentTable); /* * changeable data for user */ lastParagraph.add(new Paragraph(language.get("orderSpecification"), TR_8_I)); /* * creator data */ Paragraph creatorParagraph = new Paragraph(); creatorParagraph.add(new Phrase(language.get("orderCreator") + ": ", TR_10_B)); if (!user.getName().equals("")) { creatorParagraph.add(new Phrase(user.getName(), TR_10)); } if (!user.getPhone().equals("")) { creatorParagraph.add(new Phrase("; tel " + user.getPhone(), TR_10)); } if (!user.getEmail().equals("")) { creatorParagraph.add(new Phrase("; e-mail: " + user.getEmail(), TR_10)); } if (!user.getSkype().equals("")) { creatorParagraph.add(new Phrase("; skype: " + user.getSkype(), TR_10)); } lastParagraph.add(creatorParagraph); lastParagraph.add(emptyParagraph); /* * signature, client name and date */ Paragraph agreementParagraph = new Paragraph(language.get("agreeOrder") + ":", TR_10); agreementParagraph.setAlignment(Rectangle.ALIGN_CENTER); lastParagraph.add(agreementParagraph); lastParagraph.add(emptyParagraph); // input data table PdfPTable receiverTable = new PdfPTable(3); // te dots for data input PdfPCell dotsCell = new PdfPCell(new Phrase("............................................", TR_10_B)); dotsCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); dotsCell.setBorder(Rectangle.NO_BORDER); receiverTable.addCell(dotsCell); receiverTable.addCell(dotsCell); receiverTable.addCell(dotsCell); // date PdfPCell receiverDateCell = new PdfPCell(new Phrase(language.get("date"), TR_10)); receiverDateCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); receiverDateCell.setBorder(Rectangle.NO_BORDER); receiverTable.addCell(receiverDateCell); PdfPCell receiverNameCell = new PdfPCell(new Phrase(language.get("capitalClient"), TR_10)); receiverNameCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); receiverNameCell.setBorder(Rectangle.NO_BORDER); receiverTable.addCell(receiverNameCell); PdfPCell receiverSignatureCell = new PdfPCell(new Phrase(language.get("signature"), TR_10)); receiverSignatureCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); receiverSignatureCell.setBorder(Rectangle.NO_BORDER); receiverTable.addCell(receiverSignatureCell); lastParagraph.add(receiverTable); /* * finally add all the info to the document */ blackBoard.add(lastParagraph); try { blackBoard.close(); } catch (Exception x) { } reader = new PdfReader(temporaryByteStream.toByteArray()); try { temporaryByteStream.close(); } catch (Exception x) { } // close right after done for memory release int pageNumberAfterFinalEnd = reader.getNumberOfPages(); /* * now we make the final and last document that is ready to be sent to user */ finalDocument = new com.itextpdf.text.Document(); byteOutputStream = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(finalDocument, byteOutputStream); pageEvent.setPageCount(pageEvent.getPageCount(), true); writer.setPageEvent(pageEvent); finalDocument.open(); /* * check the last paragraph fit for our document */ if (pageNumberAfterFinalEnd > pageNumberAfterProducts) { // add the final paragraph to the new page finalDocument.add(firstParagraph); finalDocument.newPage(); finalDocument.add(emptyParagraph); finalDocument.add(lastParagraph); } else { finalDocument.add(firstParagraph); if (DOC.getProducts().size() == 0) { // we have no products, just to make it look nicer, add a blank finalDocument.add(emptyParagraph); } finalDocument.add(lastParagraph); } } catch (Exception x) { x.printStackTrace(); wasError = true; } finally { try { temporaryByteStream.close(); } catch (Exception x) { } try { byteOutputStream.close(); } catch (Exception x) { } try { blackBoard.close(); } catch (Exception x) { } try { finalDocument.close(); } catch (Exception x) { } } if (wasError) { return null; } if (byteOutputStream == null) { return null; } return byteOutputStream.toByteArray(); }