List of usage examples for com.itextpdf.text.pdf PdfReader close
public void close()
From source file:gravabncertificado007.CarimboCertificado.java
public void aplicaCarimboBin(String BN, String caminhoarquivo) throws DocumentException, IOException, RuntimeException { PdfReader.unethicalreading = true;/*from w w w. j a v a2 s. com*/ //Cria o reader para o primeiro PDF PdfReader reader = new PdfReader(caminhoarquivo); Rectangle psize = reader.getPageSize(1); float width = psize.getWidth(); float height = psize.getHeight(); Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf")); document.open(); int i = 0; BN = BN.substring(BN.length() - 13, BN.length() - 4); PdfContentByte cb = writer.getDirectContent(); while (i < reader.getNumberOfPages()) { i++; document.newPage(); PdfContentByte under = writer.getDirectContentUnder(); PdfImportedPage page1 = writer.getImportedPage(reader, i); cb.addTemplate(page1, 0, i * 0.2f); //CARIMBO DA BN BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 14); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 32, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 22, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 12, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0); cb.endText(); } document.close(); writer.close(); reader.close(); }
From source file:gravabncertificado007.CarimboCertificado.java
public void aplicaCariboGedi(String BN, String caminhoarquivo) throws DocumentException, IOException, RuntimeException { PdfReader.unethicalreading = true;/*from w w w . ja v a 2 s. co m*/ //Cria o reader para o primeiro PDF PdfReader reader = new PdfReader(caminhoarquivo); Rectangle psize = reader.getPageSize(1); float width = psize.getWidth(); float height = psize.getHeight(); Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-G.pdf")); document.open(); int i = 0; BN = BN.substring(BN.length() - 13, BN.length() - 4); PdfContentByte cb = writer.getDirectContent(); while (i < reader.getNumberOfPages()) { i++; document.newPage(); PdfContentByte under = writer.getDirectContentUnder(); PdfImportedPage page1 = writer.getImportedPage(reader, i); cb.addTemplate(page1, 0, i * 0.2f); BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 14); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " _________________ ", width / 6, 44, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 32, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 22, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |Copia Controlada |", width / 6, 28, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 16, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 12, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |_________________|", width / 6, 14, 0); cb.endText(); } document.close(); writer.close(); reader.close(); }
From source file:integrator.Pdf.java
/** * Parses a PDF to a plain text file.//from w ww . j a va2 s. c o m * @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(); reader.close(); }
From source file:io.konik.carriage.itext.ITextInvoiceAppender.java
License:Open Source License
/** * Append invoice intern./*from w w w. ja v a 2 s.com*/ * * @param appendable the appendable * @throws IOException Signals that an I/O exception has occurred. * @throws DocumentException the document exception * @throws XMPException the XMP exception */ private void appendInvoiceIntern(AppendParameter appendable) throws IOException, DocumentException, XMPException { byte[] attachmentFile = convertToByteArray(appendable.attachmentFile()); PdfReader reader = new PdfReader(appendable.inputPdf()); PdfAStamper stamper = new PdfAStamper(reader, appendable.resultingPdf(), PdfAConformanceLevel.PDF_A_3B); appendZfMetadata(stamper, appendable.zugferdConformanceLevel(), appendable.zugferdVersion()); attachFile(attachmentFile, stamper); stamper.close(); reader.close(); }
From source file:itextblast.ITextBlast.java
private static void processQAFile(String qa_filename, Boolean has_frontpage) throws IOException, DocumentException { // use one of the previous examples to create a PDF // new MovieTemplates().createPdf(MovieTemplates.RESULT); // Create a reader; from current existing file // Next time pass it from args .. PdfReader reader = new PdfReader(String.format(ITextBlast.working_dir + SOURCE, qa_filename)); ITextBlast.my_reader = reader;/*from w w w .j a v a 2 s. co m*/ // We'll create as many new PDFs as there are pages // Document document; // PdfCopy copy; // loop over all the pages in the original PDF int n = reader.getNumberOfPages(); // For test of extraction and regexp; use first 5 pages .. // n = 15; // Text Extraction Strategy here ... // LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy(); // SimpleTextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); // Both ^ does not work well; weird behavior ... no need so clever .. // START SMART Start Number ******** Pattern smart_start_pattern; smart_start_pattern = Pattern.compile(".*?SOALAN.*?N.*?O.*?(\\d+)\\b+.*", Pattern.CASE_INSENSITIVE); // Extract cover page number as smartly as possible?? String cover_page_content = PdfTextExtractor.getTextFromPage(reader, 1); Matcher smart_start_matcher = smart_start_pattern.matcher(cover_page_content); String smart_start_question_number = null; if (smart_start_matcher.find()) { // Extract the question number based on backreference smart_start_question_number = smart_start_matcher.group(1); // How will it look when using a different strategy? out.println("Matched " + smart_start_matcher.group(0) + " and SMART Start Number: " + smart_start_question_number); } // END SMART Start Number ******** Pattern liberal_found_question_pattern_uno; liberal_found_question_pattern_uno = Pattern.compile(".*N.*O.*SOALAN.*", Pattern.CASE_INSENSITIVE); Pattern liberal_found_question_pattern_dos = Pattern.compile(".*SOALAN.*N.*O.*", Pattern.CASE_INSENSITIVE); Pattern pattern_uno; // pattern = Pattern.compile("^.*NO.*SOALAN.*?(\\d+).*$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); // pattern = Pattern.compile(".*SOALAN.*?(\\d+).*", Pattern.CASE_INSENSITIVE); pattern_uno = Pattern.compile(".*N.*O.*SOALAN.*?(\\d+)\\b+.*", Pattern.CASE_INSENSITIVE); Pattern pattern_dos = Pattern.compile(".*SOALAN.*N.*O.*?(\\d+)\\b+.*", Pattern.CASE_INSENSITIVE); // OPTION 2 is to try with the next available number between word boundaries .. but may then need non-greedy .. // Init start and end page int start_page = 1; int end_page = 1; String question_number = "0-intro"; // This is for SOALAN LISAN; which has no Front Page // the Start Question Number should then be set to SMART Start Number if (!has_frontpage) { question_number = smart_start_question_number; } for (int i = 1; i < n; i++) { // init found_question_number String found_question_number = null; boolean found_match = false; // PdfDictionary page = reader.getPageN(i); // use location based strategy out.println("Page " + i); out.println("==========="); // out.println(PdfTextExtractor.getTextFromPage(reader, i, strategy)); String content = PdfTextExtractor.getTextFromPage(reader, i); // DEBUG: Uncomment below .. // out.println(content); Matcher liberal_uno_matcher = liberal_found_question_pattern_uno.matcher(content); if (liberal_uno_matcher.find()) { out.println("Matched UNO!"); found_match = true; Matcher matcher = pattern_uno.matcher(content); // Loop to find the digit; it is possible it is not found an dleft as null .. while (matcher.find()) { // Extract the question number based on backreference found_question_number = matcher.group(1); // How will it look when using a different strategy? out.println("Matched " + matcher.group(0) + " and Question Number: " + found_question_number); } } else if (liberal_found_question_pattern_dos.matcher(content).find()) { if ("0-intro".equals(question_number)) { out.println("SMART!!!"); } else { found_match = true; out.println("Matched DOS!"); Matcher matcher = pattern_dos.matcher(content); // Loop to find the digit; it is possible it is not found an dleft as null .. while (matcher.find()) { // Extract the question number based on backreference found_question_number = matcher.group(1); // How will it look when using a different strategy? out.println( "Matched " + matcher.group(0) + " and Question Number: " + found_question_number); } } } // If matched; take out the last start, end if (found_match) { // copy page over and write it down .. end_page = i - 1; if (end_page < 1) { end_page = 1; } if (null == found_question_number) { if ("0-intro".equals(question_number)) { // After intro; if got problem; try the smart start found_question_number = smart_start_question_number; out.println("First question could not determine number; using Q No. => " + found_question_number); // Print out content to debug out.println("*****DEBUG Content*******"); out.println(content); } else { // otherwise; use current question and just append Unix timestamp .. found_question_number = question_number + "_" + (System.currentTimeMillis() / 1000L); out.println( "Unexpectedly could not determine number; using Q No. => " + found_question_number); // Print out content to debug out.println("*****DEBUG Content*******"); out.println(content); } } // Write based on previous confirmed question_number ITextBlast.copySelectedQuestionPage(start_page, end_page, question_number); // re-set to current page start_page = i; end_page = i; question_number = found_question_number; } // out.println(PdfTextExtractor.getTextFromPage(reader, i)); // Pattern RegExp: #^.*NO.*SOALAN.*(\d)+$#im out.println(); out.println(); // use helper file to dump out // Look out for pattern "NO. SOALAN" // Once see pattern or reach end; snip off copy from start to end // reset start/end // else increase the end } // If end of the loop there are still straglers; mark with the special question_number = 999 if (start_page <= end_page) { // Should always happen actually .. ITextBlast.copySelectedQuestionPage(start_page, end_page, question_number); } reader.close(); }
From source file:itextblast.ITextBlast.java
public static void splitByPage(String[] args) throws IOException, DocumentException { // use one of the previous examples to create a PDF // new MovieTemplates().createPdf(MovieTemplates.RESULT); // Create a reader; from current existing file // Next time pass it from args .. PdfReader reader = new PdfReader("./source/imokman.pdf"); // We'll create as many new PDFs as there are pages Document document;//from w ww. j a v a2 s . c o m PdfCopy copy; // loop over all the pages in the original PDF int n = reader.getNumberOfPages(); for (int i = 0; i < n;) { // step 1 document = new Document(); // step 2 copy = new PdfCopy(document, new FileOutputStream(String.format(RESULT, ++i))); // step 3 document.open(); // step 4 copy.addPage(copy.getImportedPage(reader, i)); // step 5 document.close(); } reader.close(); }
From source file:javaapplication1.PDF.java
public void extractImages(String filename) throws IOException, DocumentException { // System.out.println("Processing PDF at " + filename); PdfReader reader = new PdfReader(filename); PdfReaderContentParser parser = new PdfReaderContentParser(reader); listener = new ImageRenderListener(); RenderListener print = parser.processContent(3, listener); reader.close(); }
From source file:Logic.AddCover1.java
/** * Manipulates a PDF file src with the file dest as result * @param src the original PDF/*w w w .j a v a 2s .com*/ * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest, String cov) throws IOException, DocumentException { PdfReader cover = new PdfReader(cov); PdfReader reader = new PdfReader(src); Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest)); document.open(); copy.addDocument(cover); copy.addDocument(reader); document.close(); cover.close(); reader.close(); }
From source file:Logica.LogicaReserva.java
private void GenerarDocumento(Reserva nuevaReserva) throws IOException, DocumentException { //String dirPath = "C:\\"; String fileName = "Base reserva.pdf"; HashMap fieldsWithValues = new HashMap(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfReader reader = new PdfReader(fileName); PdfStamper stamper = new PdfStamper(reader, baosPDF); AcroFields form = stamper.getAcroFields(); HashMap fields = (HashMap) form.getFields(); Set keys = fields.keySet();// w ww . ja va 2 s .c o m //Metodo que retorna map de datos que queremos obtener de objeto para agregar a PDF fieldsWithValues = crearHashMapReserva(nuevaReserva, keys); //Iteracion sobre campos de pdf Iterator itr = keys.iterator(); while (itr.hasNext()) { String fieldName = (String) itr.next(); String fieldValue = fieldsWithValues.get(fieldName) != null ? (String) (fieldsWithValues.get(fieldName)) : ""; form.setField(fieldName, fieldValue); form.setFieldProperty(fieldName, "setfflags", PdfFormField.FF_READ_ONLY, null); } stamper.setFormFlattening(true); stamper.close(); reader.close(); //Guardando cambios String nombre; DateFormat fecha = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss"); nombre = fecha.format(nuevaReserva.getFechaHasta()); String nombreydir = "Documentos\\Documento Reserva -" + nombre + "-.pdf"; OutputStream pdf = new FileOutputStream(nombreydir); baosPDF.writeTo(pdf); pdf.close(); Hilo h1 = new Hilo("email", nombreydir, nuevaReserva.getCliente().getCorreo()); h1.start(); try { File archivo = new File(nombreydir); Desktop.getDesktop().open(archivo); } catch (IOException ex) { } //EnvioEmail(nombreydir, nuevaReserva.getCliente().getCorreo()); }
From source file:me.Aron.Heinecke.fbot.lib.Converter.java
License:Apache License
/*** * Return the amount of sites in a pdf/* w ww. j a va 2 s . co m*/ * using a deprecated (working) iText function * @param file path of the file to use * @return amount of sites */ @SuppressWarnings("deprecation") public int pdfSites(String file) { try { RandomAccessFile raf = new RandomAccessFile(new File(file), "r"); RandomAccessFileOrArray pdfFile; pdfFile = new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(raf)); PdfReader reader = new PdfReader(pdfFile, new byte[0]); int pages = reader.getNumberOfPages(); reader.close(); return pages; } catch (InvalidPdfException e) { fbot.getLogger().severe("converter", "Invalid PDF file!: no index"); } catch (Exception e) { fbot.getLogger().exception("converter", e); } return -1; }