List of usage examples for com.itextpdf.text.pdf PdfReader close
public void close()
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] personalize(byte[] pdf, Contact contact, Toc tableOfContents) throws IOException, DocumentException { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdf); final PdfStamper stamper = new PdfStamper(reader, bos); // stamp some text on first page PdfContentByte text = stamper.getOverContent(1); text.beginText();// w w w .ja v a 2 s . c o m text.setColorFill(iTextUtil.getFontCoverText().getColor()); text.setFontAndSize(iTextUtil.getFontCoverText().getBaseFont(), iTextUtil.getFontCoverText().getSize()); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle1, text.getPdfDocument().getPageSize().getWidth() - 15, 195, 0); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle2, text.getPdfDocument().getPageSize().getWidth() - 15, 175, 0); text.showTextAligned(Element.ALIGN_RIGHT, contact.getCurrency().getTitlePageDescription(), text.getPdfDocument().getPageSize().getWidth() - 15, 80, 0); text.setColorFill(iTextUtil.getFontCoverPricingguide().getColor()); text.setFontAndSize(iTextUtil.getFontCoverPricingguide().getBaseFont(), iTextUtil.getFontCoverPricingguide().getSize()); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle3, text.getPdfDocument().getPageSize().getWidth() - 15, 145, 0); text.setColorFill(iTextUtil.getFontCoverYear().getColor()); text.setFontAndSize(iTextUtil.getFontCoverYear().getBaseFont(), iTextUtil.getFontCoverYear().getSize()); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle4, text.getPdfDocument().getPageSize().getWidth() - 15, 105, 0); text.endText(); // stamp some text on first page of the table of contents page final Image logoImage = iTextUtil.getImageFromByteArray(HttpUtil.readByteArray( pdfTemplate.getLogo().getUrl(), defaultService.getUserName(), defaultService.getPassword())); final PdfContentByte tocContent = stamper.getOverContent(tableOfContents.getFirstPageOfToc()); final float resizeRatio = logoImage.getHeight() / 85; // define the desired height of the log tocContent.addImage(logoImage, logoImage.getWidth() / resizeRatio, 0, 0, logoImage.getHeight() / resizeRatio, 59, 615); text = stamper.getOverContent(tableOfContents.getFirstPageOfToc()); text.beginText(); text.setColorFill(iTextUtil.getFontPersonalization().getColor()); text.setFontAndSize(iTextUtil.getFontPersonalization().getBaseFont(), iTextUtil.getFontPersonalization().getSize()); text.showTextAligned(Element.ALIGN_LEFT, "Prepared for:", 355, 681, 0); text.showTextAligned(Element.ALIGN_LEFT, contact.getFullName(), 355, 662, 0); // set company name if (!StringUtils.isEmpty(contact.getCompany())) { text.showTextAligned(Element.ALIGN_LEFT, contact.getCompany(), 355, 643, 0); text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355, 624, 0); } else { text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355, 643, 0); } text.endText(); final ColumnText ct = new ColumnText(tocContent); ct.setSimpleColumn(new Rectangle(55, 517, iTextUtil.PAGE_SIZE.getWidth() - 45, 575)); final List<Element> elements = HTMLWorker.parseToList(new StringReader(disclaimer), null); final Paragraph p = new Paragraph(); p.setAlignment(Element.ALIGN_JUSTIFIED); for (Element element : elements) { for (Chunk chunk : element.getChunks()) { chunk.setFont(iTextUtil.getFontDisclaimer()); } p.add(element); } ct.addElement(p); ct.go(); stamper.close(); reader.close(); return bos.toByteArray(); } }
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] createBookmarks(byte[] pdf, Toc tableOfContents) throws DocumentException, IOException { // create the bookmarks final List<HashMap<String, Object>> outlines = new ArrayList<>(); final List<TocEntry> entriesSorted = tableOfContents.getEntriesSorted(); final List<HashMap<String, Object>> modelBookmarkKids = new ArrayList<>(); HashMap<String, Object> modelBookmark; for (TocEntry tocEntry : entriesSorted) { if (tocEntry.isIncludedInToc()) { final HashMap<String, Object> bookmark = new HashMap<>(); String name = tocEntry.getName(); name = name.replaceAll("<sup>", ""); name = name.replaceAll("</sup>", ""); name = name.replaceAll("<i.*?>", ""); name = name.replaceAll("</i>", ""); name = GreekAlphabet.replaceGreekHtmlCodesWithUnicode(name); bookmark.put("Title", name); bookmark.put("Action", "GoTo"); bookmark.put("Page", String.format("%d Fit", tocEntry.getFinalPageNumber())); if (tocEntry.getLevel() == 1) { outlines.add(bookmark);//from ww w . j a v a 2s . co m } else { modelBookmarkKids.add(bookmark); } if (tocEntry.isModelHeader()) { modelBookmark = bookmark; modelBookmark.put("Open", true); modelBookmark.put("Kids", modelBookmarkKids); } } } try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdf); final PdfStamper stamper = new PdfStamper(reader, bos); stamper.setOutlines(outlines); stamper.close(); reader.close(); return bos.toByteArray(); } }
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] stampTableOfContents(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdf); final PdfStamper stamper = new PdfStamper(reader, bos); // stamp the named destinations for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) { stamper.addNamedDestination("page" + pageNumber, pageNumber, new PdfDestination(PdfDestination.XYZ, 80f, 800f, 0)); }// w ww. java2 s .c o m // create the table of contents final Chunk tocTitle = new Chunk("TABLE OF CONTENTS", iTextUtil.getFontTocTitle()); int currentTocPage = tableOfContents.getFirstPageOfToc(); int firstTocPage = currentTocPage; PdfContentByte canvas = stamper.getOverContent(currentTocPage); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(tocTitle), 55, 470, 0); final List<TocEntry> entriesSorted = tableOfContents.getEntriesSorted(); int tocEntryNumber = 0; for (TocEntry tocEntry : entriesSorted) { if (tocEntry.isIncludedInToc()) { tocEntryNumber++; // take the right TOC page to stamp the TOC entry on (needed for TOC's with multiple pages) if (tocEntryNumber == getNumberOfItemsPerTocPage(0) || (tocEntryNumber > getNumberOfItemsPerTocPage(0) && (tocEntryNumber - getNumberOfItemsPerTocPage(0)) % getNumberOfItemsPerTocPage(currentTocPage - firstTocPage) == 0)) { currentTocPage++; canvas = stamper.getOverContent(currentTocPage); } Font font = iTextUtil.getFontToc(); if (tocEntry.getLevel() == 1) { font = iTextUtil.getFontTocBold(); } final Phrase p = processHtmlCodes(tocEntry.getLevelString() + tocEntry.getName(), font, iTextUtil.getFontTocSymbol()); p.add(new Chunk("", iTextUtil.getFontToc())); if (tocEntry.isShowingPageNumber()) { p.add(new Chunk(new DottedLineSeparator())); p.add(new Chunk(" " + String.valueOf(tocEntry.getFinalPageNumber()), iTextUtil.getFontToc())); } for (Chunk chunk : p.getChunks()) { chunk.setAction(PdfAction.gotoLocalPage("page" + tocEntry.getFinalPageNumber(), false)); } int y; if (tocEntryNumber < getNumberOfItemsPerTocPage(0)) { y = 460 - (16 * (tocEntryNumber % getNumberOfItemsPerTocPage(0))); } else { y = 680 - (16 * ((tocEntryNumber - getNumberOfItemsPerTocPage(0)) % getNumberOfItemsPerTocPage(currentTocPage - firstTocPage))); } final ColumnText ct = new ColumnText(canvas); ct.setSimpleColumn(p, 52, y, 555, 70, 0, Element.ALIGN_JUSTIFIED); ct.go(); } } stamper.close(); reader.close(); return bos.toByteArray(); } }
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] enableLinkToWebsite(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdf); final PdfStamper stamper = new PdfStamper(reader, bos); for (int i = tableOfContents.getFirstPageOfToc(); i <= tableOfContents .getLastPageNumberOfModelPages(); i++) { final Chunk websiteChunk = new Chunk(".................."); websiteChunk.setAction(new PdfAction(websiteLink)); ColumnText ct = new ColumnText(stamper.getUnderContent(i)); ct.setSimpleColumn(335, 10, 400, 35); ct.addText(new Phrase(websiteChunk)); ct.go();/*from w w w . j av a 2s . c om*/ final Chunk emailChunk = new Chunk("........................................."); emailChunk.setAction(new PdfAction(emailLink)); ct = new ColumnText(stamper.getUnderContent(i)); ct.setSimpleColumn(240, 10, 330, 35); ct.addText(new Phrase(emailChunk)); ct.go(); } stamper.close(); reader.close(); return bos.toByteArray(); } }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
License:Open Source License
public static byte[] setPageNumbers(byte[] pdfDocument) throws IOException, DocumentException { final int numberOfPages = numberOfPages(pdfDocument); if (numberOfPages > 1) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdfDocument); final PdfStamper stamper = new PdfStamper(reader, baos); for (int pageNumber = 2; pageNumber <= numberOfPages; pageNumber++) { // get the first page final PdfContentByte canvas = stamper.getOverContent(pageNumber); // stamp the footer on the page final ColumnText ct = new ColumnText(canvas); ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase(pageNumber + "", getFontPageNumber()), 550, 22, 0); ct.go();//from w w w .j ava 2 s. c om } // close out stamper.close(); reader.close(); return baos.toByteArray(); } } return pdfDocument; }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
License:Open Source License
public static byte[] organize(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException { try (final ByteArrayOutputStream copyBaos = new ByteArrayOutputStream()) { final Document doc = new Document(); final PdfCopy copy = new PdfSmartCopy(doc, copyBaos); final PdfReader reader = new PdfReader(pdf); reader.selectPages(tableOfContents.getPageSequence()); doc.open();/*from ww w .j a va 2s .com*/ for (int i = 1; i <= reader.getNumberOfPages(); i++) { copy.addPage(copy.getImportedPage(reader, i)); } reader.close(); copy.close(); return copyBaos.toByteArray(); } }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
License:Open Source License
public static Image getImageFromPdf(byte[] pdf) throws IOException, BadElementException { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdf); final PdfReaderContentParser parser = new PdfReaderContentParser(reader); final ImageRenderListener listener = new ImageRenderListener(bos); parser.processContent(1, listener); reader.close(); return Image.getInstance(bos.toByteArray()); }// w w w . j a v a 2 s .c om }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
License:Open Source License
public static byte[] embedFont(byte[] pdf, String fontFileName, String fontName) throws IOException, DocumentException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { // the font file RandomAccessFile raf = new RandomAccessFile(fontFileName, "r"); byte fontfile[] = new byte[(int) raf.length()]; raf.readFully(fontfile);//from w w w . j a v a 2 s . c o m raf.close(); // create a new stream for the font file PdfStream stream = new PdfStream(fontfile); stream.flateCompress(); stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length)); // create a reader object PdfReader reader = new PdfReader(pdf); int n = reader.getXrefSize(); PdfObject object; PdfDictionary font; PdfStamper stamper = new PdfStamper(reader, baos); PdfName fontname = new PdfName(fontName); for (int i = 0; i < n; i++) { object = reader.getPdfObject(i); if (object == null || !object.isDictionary()) continue; font = (PdfDictionary) object; if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE1)) && fontname.equals(font.get(PdfName.FONTNAME))) { PdfIndirectObject objref = stamper.getWriter().addToBody(stream); font.put(PdfName.FONTFILE2, objref.getIndirectReference()); } } stamper.close(); reader.close(); return baos.toByteArray(); } }
From source file:bflows.FattureManagement.java
public void processPDF() { // Document pdf = null; BufferedWriter writer = null; consumi = new ArrayList<Consumo>(); lines = new ArrayList<String>(); try {/*from w w w. ja v a2 s.com*/ // Salvo file temporaneo per debugging //outputFile = new File("C:\\Users\\nklma\\Documents\\NetBeansProjects\\temp", "temp.txt"); //writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile))); //FileOutputStream fileOutputStream = new FileOutputStream("extracted.txt"); // iText Library PdfReader pdfReader = new PdfReader(inputStream); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { SimpleTextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); String currentText = PdfTextExtractor.getTextFromPage(pdfReader, page, strategy); String[] l = currentText.split("\n"); for (int i = 0; i < l.length; i++) lines.add(l[i]); } pdfReader.close(); //for(String line : lines) //{ // writer.write(line); // writer.newLine(); //} //writer.close(); boolean startPointFound = false; boolean dateFound = false; boolean totaleFound = false; boolean contributiFound = false; boolean prodottiFound = false; boolean altriFound = false; boolean ivaFound = false; Consumo consumo = null; for (String line : lines) { //recupero data fattura if (!dateFound) { if (line.contains("Emessa")) { String cleanLine = line.replaceAll("\\s+", " "); String[] splitted = cleanLine.split(" "); for (String s : splitted) { if (s.contains("/")) { s = s.replace("/", "-"); data = s; } } dateFound = true; } } //recupero totale fattura con iva if (!totaleFound) { if (line.contains("IMPORTO")) { String cleanLine = line.replaceAll("\\s+", " ").replaceAll("_", ""); String importo = cleanLine.replace("IMPORTO: ", "").replace("Euro", "").trim(); totale = Double.parseDouble(importo.replace(".", "").replace(",", ".")); totaleFound = true; } } //recupero importo contributi e abbonamenti if (!contributiFound) { if (line.contains("CONTRIBUTI E ABBONAMENTI")) { String cleanLine = line.replaceAll("\\s+", " "); String importo = cleanLine.replace("CONTRIBUTI E ABBONAMENTI ", ""); contributi = Double.parseDouble(importo.replace(".", "").replace(",", ".")); contributiFound = true; } } //recupero importo prodotti (noleggi) // SOLO PER 2017+ if (data != null && Integer.parseInt(data.split("-")[2]) >= 2017 && !prodottiFound) { if (line.contains("PRODOTTI")) { String cleanLine = line.replaceAll("\\s+", " "); String importo = cleanLine.replace("PRODOTTI ", ""); prodotti = Double.parseDouble(importo.replace(".", "").replace(",", ".")); prodottiFound = true; } } //recupero importo altri addebiti e accrediti if (!altriFound) { if (line.contains("ALTRI ADDEBITI E ACCREDITI")) { String cleanLine = line.replaceAll("\\s+", " "); String importo = cleanLine.replace("ALTRI ADDEBITI E ACCREDITI ", ""); altri = Double.parseDouble(importo.replace(".", "").replace(",", ".")); altriFound = true; } } //recupero importo IVA if ((contributiFound || altriFound) && !ivaFound) // in questo modo si evitano match con "partita iva" ecc { if (line.contains("IVA")) { String cleanLine = line.replaceAll("\\s+", " "); String importo = cleanLine.replace("IVA ", ""); iva = Double.parseDouble(importo.replace(".", "").replace(",", ".")); ivaFound = true; } } //Il primo RIEPILOGO PER UTENZA segna l'inizio della tabella dei consumi da analizzare if (!startPointFound && line.contains("RIEPILOGO PER UTENZA")) startPointFound = !startPointFound; if (!startPointFound) continue; //SERVIZI OPZIONALI segna la fine della tabella if (line.matches("SERVIZI OPZIONALI")) { consumi.add(consumo); return; } if (Integer.parseInt(data.split("-")[2]) >= 2017) { // ------------------------------ // PER FATTURE SUCCESSIVE AL 2017 // ------------------------------ ArrayList<String> splitted; splitted = StringMatcher.matches(line, "\\bLinea\\b\\s((\\d{10}))"); //if(line.matches("(?:(?:Linea)\\s)(\\d{10})")) if (!splitted.isEmpty()) { // Nuovo consumo if (consumo != null) //salvo la precedente { consumi.add(consumo); } //creo un nuovo consumo consumo = new Consumo(); StringBuilder str = new StringBuilder(splitted.get(0)); str.insert(3, "-"); consumo.Telefono = str.toString(); } splitted = StringMatcher.matches(line, "((?:\\w+\\s|\\w+-\\w+\\s)+)(?:\\d{2}\\/\\d{2}\\/\\d{4}\\s)((?:\\D+\\s)+)(?:\\d{2}\\/\\d{2}-\\d{2}\\/\\d{2}\\s)((\\d+,\\d+))$"); //if(line.matches("(?:(?:(?:\w+\s)+\w+\-)?(?:\w+\s)+)(?:\d{2}\/\d{2}\/\d{4})\s((?:\w+\s)+)(?:\d{2}\/\d{2}\-\d{2}\/\d{2})\s(\d+,\d+)")) if (!splitted.isEmpty()) { // Contributi o abbonamenti if (consumo != null) { String lel = splitted.get(1); if (splitted.get(1).contains("Contributi")) consumo.CRB += Double.parseDouble(splitted.get(2).replace(",", ".")); else if (splitted.get(1).contains("Abbonamenti")) consumo.ABB += Double.parseDouble(splitted.get(2).replace(",", ".")); } } splitted = StringMatcher.matches(line, "\\bRicariche\\b(?:\\s\\w+)+(?:\\s\\d\\s)((\\d+,\\d+))$"); if (!splitted.isEmpty()) //if(line.matches("(Ricariche(?:\\s\\w+)+)(\\s\\d\\s)(\\d+,\\d+)")) { // Ricariche //splitted = SplitLine.splitNewRicarica(line); if (consumo != null) { consumo.AAA += Double.parseDouble(splitted.get(0).replace(",", ".")); } } splitted = StringMatcher.matches(line, "\\bTotale\\b\\s((\\d+,\\d+))$"); //if(line.matches("(Totale\\s+)(\\d+,\\d+)")) if (!splitted.isEmpty()) { // Totale //splitted = SplitLine.splitNewTotale(line); if (consumo != null) { consumo.Totale += Double.parseDouble(splitted.get(0).replace(",", ".")); } } } else { // ------------------------------ // PER FATTURE PRECEDENTI AL 2017 // ------------------------------ // Linea e consumo if (line.matches("(\\d{3}(\\s+)?-(\\s+)?\\d{7})((?:\\s+)(?:\\w+\\s+)+)(\\d+,\\d+)")) // (3 digits)(optional whitespaces)-(optional whitespaces)(7 digits) // (any number of whitespaces)(any number of words followed by whitespace)(1+ digits),(1+digits) { //elimino gli spazi nel numero di telefono line = line.replace(" - ", "-"); //se entro qui significa che inizia un consumo ArrayList<String> splitted = SplitLine.splitConsumo1(line); //esiste un consumo con lo stesso numero quindi i dati vanno aggiunti if (consumo != null && splitted.get(0).replaceAll("\\s+", "").equals(consumo.Telefono)) // il continuo del precedente { if (splitted.get(1).contains("Contributi")) consumo.CRB = Double.parseDouble(splitted.get(2).replace(",", ".")); else if (splitted.get(1).contains("Altri")) consumo.AAA = Double.parseDouble(splitted.get(2).replace(",", ".")); else if (splitted.get(1).contains("Abbonamenti")) consumo.ABB = Double.parseDouble(splitted.get(2).replace(",", ".")); } else { //non esiste un consumo con il numero letto if (consumo != null) //salvo la precedente { consumi.add(consumo); } //creo un nuovo consumo consumo = new Consumo(); consumo.Telefono = splitted.get(0); if (splitted.get(1).contains("Contributi")) consumo.CRB = Double.parseDouble(splitted.get(2).replace(",", ".")); else if (splitted.get(1).contains("Altri")) consumo.AAA = Double.parseDouble(splitted.get(2).replace(",", ".")); else if (splitted.get(1).contains("Abbonamenti")) consumo.ABB = Double.parseDouble(splitted.get(2).replace(",", ".")); } } if (line.matches("((?:\\w+\\s+)+)(\\d+,\\d+)"))//(any number of words followed by whitespaces)(1+ digits),(1+ digits) { //continua la fattura precedente ArrayList<String> splitted = SplitLine.splitConsumo2(line); if (consumo != null) { if (splitted.get(0).contains("Contributi")) consumo.CRB = Double.parseDouble(splitted.get(1).replace(",", ".")); else if (splitted.get(0).contains("Altri")) consumo.AAA = Double.parseDouble(splitted.get(1).replace(",", ".")); else if (splitted.get(0).contains("Abbonamenti")) consumo.ABB = Double.parseDouble(splitted.get(1).replace(",", ".")); else if (splitted.get(0).contains("Totale")) consumo.Totale = Double.parseDouble(splitted.get(1).replace(",", ".")); } } } } //outputFile.delete(); } catch (IOException ex) { EService.logAndRecover(ex); setResult(EService.UNRECOVERABLE_ERROR); setErrorMessage("FattureManagement.ProcessPDF(): " + ex.getMessage()); } catch (NumberFormatException ex) { EService.logAndRecover((FatalError) ex); setResult(EService.UNRECOVERABLE_ERROR); setErrorMessage("FattureManagement.ProcessPDF(): " + ex.getMessage()); } }
From source file:br.com.smarttaco.util.HelenaBarbosa.java
/** * pdf2txt//from ww w . ja v a 2s. co m * * @param pdf * @param paginas se for <code>null</code> realiza leitura completa. * @param txt * @throws FileNotFoundException * @throws IOException */ private static void pdf2txt(final String pdf, List<Integer> paginas, final String txt) throws FileNotFoundException, IOException { PdfReader reader = new PdfReader(pdf); //System.out.println(reader.getInfo().toString()); if (paginas != null) { reader.selectPages(paginas); } PdfReaderContentParser parser = new PdfReaderContentParser(reader); PrintWriter out = new PrintWriter(txt, "UTF-8"); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); out.println(strategy.getResultantText()); } out.flush(); out.close(); reader.close(); }