List of usage examples for com.itextpdf.text.pdf PdfCopy close
@Override public void close()
Document
was closed and that no other Elements
will be added. From source file:Separator.java
License:Apache License
public static void splitPDFFile(String fileName) { // splitting "documents" up by consecutive orientations try {/*w ww. ja va 2 s . c o m*/ int[] oriens = new int[pReader.getNumberOfPages()]; ArrayList<Integer> splitSizes = new ArrayList<Integer>(); int splitSize = 1; int position = 0; for (int i = 1; i <= pReader.getNumberOfPages(); i++) { String picName = System.getProperty("user.home") + "\\Desktop\\Scan Folder\\Temp Pictures\\my_image_" + i + ".jpg"; oriens[i - 1] = getOrientation(new Picture(picName)); System.out.print(oriens[i - 1]); if (i == 1) { splitSizes.add(1); } else if (oriens[i - 1] == oriens[i - 2]) { splitSize++; if (i == pReader.getNumberOfPages()) { splitSizes.set(position, splitSize); } } else if (oriens[i - 1] != oriens[i - 2]) { splitSizes.set(position, splitSize); position++; splitSizes.add(1); splitSize = 1; } else { System.out.println("Error"); } } System.out.println("\n\n" + splitSizes); System.out.println("\nSuccessfully read input file: " + fileName + "\n"); int totalPages = pReader.getNumberOfPages(); System.out.println("There are total " + totalPages + " pages in this input file\n"); split = 0; // Page numbers start from 1 to n; writing each set of pages to one file for (int pageNum = 1; pageNum <= totalPages; pageNum += splitSizes.get(split - 1)) { String outFile = System.getProperty("user.home") + "\\Desktop\\Scan Folder\\Temp PDFs\\temp_" + split + ".pdf"; Document document = new Document(pReader.getPageSizeWithRotation(pageNum)); PdfCopy writer = new PdfCopy(document, new FileOutputStream(outFile)); document.open(); int tempPageCount = 0; for (int pN = 0; pN < splitSizes.get(split); pN++) { PdfImportedPage page = writer.getImportedPage(pReader, pageNum + pN); writer.addPage(page); tempPageCount++; } System.out.println("pageNum: " + pageNum + " splitSizes.get(split): " + splitSizes.get(split)); document.close(); /* * The following will trigger the PDF file being written to the * system */ writer.close(); crop(outFile, fileName, split, verFlag); System.out.println("Split: [" + tempPageCount + " page]: " + outFile); split++; verFlag = !verFlag; // alternating to determine the cropped orientation of the PDF } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "There was an error while splitting up\n" + "the PDF.", "Error!", JOptionPane.OK_OPTION); System.exit(0); } }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
License:Open Source License
public static byte[] merge(byte[]... pdfAsBytes) throws DocumentException, IOException { try (final ByteArrayOutputStream copyBaos = new ByteArrayOutputStream()) { final Document doc = new Document(); final PdfCopy copy = new PdfSmartCopy(doc, copyBaos); doc.open();/* www . j a v a 2s. c om*/ int numberOfPages = 0; final java.util.List<HashMap<String, Object>> bookmarks = new ArrayList<>(); PdfReader pdf = null; for (byte[] pdfAsByte : pdfAsBytes) { if (pdfAsByte != null && pdfAsByte.length > 0) { pdf = new PdfReader(pdfAsByte); pdf.consolidateNamedDestinations(); final List<HashMap<String, Object>> pdfBookmarks = SimpleBookmark.getBookmark(pdf); if (!CollectionUtils.isEmpty(pdfBookmarks)) { SimpleBookmark.shiftPageNumbers(pdfBookmarks, numberOfPages, null); bookmarks.addAll(pdfBookmarks); } for (int i = 1; i <= pdf.getNumberOfPages(); i++) { copy.addPage(copy.getImportedPage(pdf, i)); } numberOfPages += pdf.getNumberOfPages(); } } if (pdf != null) { SimpleNamedDestination.getNamedDestination(pdf, false); } if (!CollectionUtils.isEmpty(bookmarks)) { copy.setOutlines(bookmarks); } copy.close(); return copyBaos.toByteArray(); } }
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 w ww .j av a 2 s. c o m*/ for (int i = 1; i <= reader.getNumberOfPages(); i++) { copy.addPage(copy.getImportedPage(reader, i)); } reader.close(); copy.close(); return copyBaos.toByteArray(); } }
From source file:com.betel.flowers.pdf.util.RemoveBlankPageFromPDF.java
public static void removeBlankPdfPages(String source, String destination) throws IOException, DocumentException { PdfReader r = null;//from w w w.j a v a 2 s. co m RandomAccessSourceFactory rasf = null; RandomAccessFileOrArray raf = null; Document document = null; PdfCopy writer = null; try { r = new PdfReader(source); // deprecated // RandomAccessFileOrArray raf // = new RandomAccessFileOrArray(pdfSourceFile); // itext 5.4.1 rasf = new RandomAccessSourceFactory(); raf = new RandomAccessFileOrArray(rasf.createBestSource(source)); document = new Document(r.getPageSizeWithRotation(1)); writer = new PdfCopy(document, new FileOutputStream(destination)); document.open(); PdfImportedPage page = null; for (int i = 1; i <= r.getNumberOfPages(); i++) { // first check, examine the resource dictionary for /Font or // /XObject keys. If either are present -> not blank. PdfDictionary pageDict = r.getPageN(i); PdfDictionary resDict = (PdfDictionary) pageDict.get(PdfName.RESOURCES); boolean noFontsOrImages = true; if (resDict != null) { noFontsOrImages = resDict.get(PdfName.FONT) == null && resDict.get(PdfName.XOBJECT) == null; } if (!noFontsOrImages) { byte bContent[] = r.getPageContent(i, raf); ByteArrayOutputStream bs = new ByteArrayOutputStream(); bs.write(bContent); if (bs.size() > BLANK_THRESHOLD) { page = writer.getImportedPage(r, i); writer.addPage(page); } } } } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } if (raf != null) { raf.close(); } if (r != null) { r.close(); } } }
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfSplitCopy(String path) throws IOException, DocumentException { // TODO Instead of hard code path, pass in as argument File folder = new File(path); FileNameFilter FileFilter = new FileNameFilter(); File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */ for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; }//from ww w .j a v a 2 s.co m // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); PdfReader pdfFileReader = new PdfReader(file.getPath()); Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); /* instantiates a new document to be made */ String[] fileNameNum = fileNameWithoutExt.split("-"); int fileNameNumOne = Integer.getInteger(fileNameNum[0]); int fileNameNumTwo = Integer.getInteger(fileNameNum[1]); int constant = 1; int k = 0; int numPages = fileNameNumTwo - fileNameNumOne; // Split on a space '\s' // Determine number of pages by difference of lot numbers // Read in the source document // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf // Create a copy of the orignal source file. We will pick specific pages out below document.open(); for (int j = 0; j < numPages + 1; j++) { String FileName = (fileNameWithoutExt); /* Dynamic file name */ PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf")); deleteFile[k] = (path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf"); k++; document.open(); copy.addPage( copy.getImportedPage(pdfFileReader, constant)); /* Import pages from original document */ if (j == 1) { newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } else if (j > 1) { newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } document.close(); copy.close(); } System.out.println("Number of Documents Created:" + numPages); pdfFileReader.close(); } }
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfSplitSupplierDoc(String path) throws IOException, DocumentException { // TODO Instead of hard code path, pass in as argument File folder = new File(path); FileNameFilter FileFilter = new FileNameFilter(); File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */ for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; }/*w w w. ja v a 2s . c om*/ // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); PdfReader pdfFileReader = new PdfReader(file.getPath()); Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); /* instantiates a new document to be made */ String[] fileNames = fileNameWithoutExt.split("-"); /* * if (fileNames.length != 2) { throw new RuntimeException("File name format is not in right format"); } */ String fileNameFirst = fileNames[1]; String fileNameSecond = fileNames[2]; System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond); // Project num is always the 1st part String projectNum = fileNames[0]; if (!projectNum.equals(fileNames[0])) { throw new RuntimeException("Filename needs to have a project number"); } // Strip off the first and second lot number, parse into integers int firstLotNum; int secondLotNum; firstLotNum = Integer.parseInt(fileNames[1]); secondLotNum = Integer.parseInt(fileNames[2].substring(0, fileNames[2].lastIndexOf("."))); // Create a copy of the orignal source file. We will pick specific pages out below document.open(); int numPages = secondLotNum - firstLotNum; for (int j = 1; j < numPages + 1; j++) { String FileName = projectNum + "-" + (firstLotNum) + ".pdf"; /* Dynamic file name */ firstLotNum++; document = new Document(PageSize.LETTER, 0, 0, 0, 0); PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName)); document.open(); copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */ document.close(); copy.close(); } pdfFileReader.close(); } }
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfSplitDrop(File[] files) throws IOException, DocumentException, InterruptedException { // TODO Instead of hard code path, pass in as argument String path;// ww w . j a va 2 s .c o m if (directoryField.getText().isEmpty() || directoryField.getText().equals(example)) { path = files[0].getParent(); } else { path = directoryField.getText(); } File[] listOfFiles = files; /* Stores the listing of the files */ for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; } // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); PdfReader pdfFileReader = new PdfReader(file.getPath()); Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); /* instantiates a new document to be made */ int numPages = pdfFileReader.getNumberOfPages(); // Determine number of pages by difference of lot numbers // Read in the source document // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf // Create a copy of the orignal source file. We will pick specific pages out below int k = 0; for (int j = 1; j < numPages + 1; j++) { String FileName = fileNameWithoutExt; /* Dynamic file name */ PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName + "(" + j + ")" + ".pdf")); document.open(); copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */ deleteFile[k] += path + "\\" + FileName + "(" + j + ")" + ".pdf"; k++; if (j == 1) { newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } else if (j > 1) { newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } document.close(); copy.close(); } pdfFileReader.close(); } }
From source file:de.mat.utils.pdftools.PdfExtractEmptyPages.java
License:Mozilla Public License
/** * <h4>FeatureDomain:</h4>/*w ww. j a v a 2 s . com*/ * PublishingTools * <h4>FeatureDescription:</h4> * reads pdfSourceFile and adds pages to pdfRemovedFile if empty, or to * pdfDestinationFile if not empty * <h4>FeatureResult:</h4> * <ul> * <li>updates pdfDestinationFile - add all pages which are not empty * <li>updates pdfRemovedFile - add all empty pages * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param pdfSourceFile - source pdf-file * @param pdfDestinationFile - pdf with all not empty pages * @param pdfRemovedFile - pdf with all empty pages * @throws Exception */ public static void removeBlankPdfPages(String pdfSourceFile, String pdfDestinationFile, String pdfRemovedFile) throws Exception { // create readerOrig PdfReader readerOrig = new PdfReader(pdfSourceFile); // create writerTrimmed which bases on readerOrig Document documentTrimmed = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerTrimmed = new PdfCopy(documentTrimmed, new FileOutputStream(pdfDestinationFile)); documentTrimmed.open(); // create writerRemoved which bases on readerOrig Document documentRemoved = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerRemoved = new PdfCopy(documentRemoved, new FileOutputStream(pdfRemovedFile)); documentRemoved.open(); // extract and copy empty pages addTrimmedPages(pdfSourceFile, readerOrig, writerTrimmed, writerRemoved, true); // close everything documentTrimmed.close(); writerTrimmed.close(); documentRemoved.close(); writerRemoved.close(); readerOrig.close(); }
From source file:de.mat.utils.pdftools.PdfMerge.java
License:Mozilla Public License
/** * <h4>FeatureDomain:</h4>/*from w w w. j a va2 s . c o m*/ * PublishingTools * <h4>FeatureDescription:</h4> * merge pdfs from lstBookMarks to fileNew and trim empty pages if flgTrim * is set * <h4>FeatureResult:</h4> * <ul> * <li>create PDF - fileNew * <li>updates lstBookMarks - updates PAGE (firstPageNum) and * PAGES (countPage= per Bookmark * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param lstBookMarks - list of Bookmark (files to merge) * @param fileNew - destination PDF filename * @param flgTrim - trim empty pages * @throws Exception */ public static void mergePdfs(List<Bookmark> lstBookMarks, String fileNew, boolean flgTrim) throws Exception { // FirstFile Map curBookMark = (Map) lstBookMarks.get(0); String curFileName = (String) curBookMark.get("SRC"); // Neues Dokument anlegen aus 1. Quelldokument anlegen PdfReader reader = new PdfReader(curFileName); Document documentNew = new Document(reader.getPageSizeWithRotation(1)); reader.close(); PdfCopy writerNew = new PdfCopy(documentNew, new FileOutputStream(fileNew)); documentNew.open(); int siteNr = 1; for (Iterator iter = lstBookMarks.iterator(); iter.hasNext();) { curBookMark = (Map) iter.next(); curFileName = (String) curBookMark.get("SRC"); if (LOGGER.isInfoEnabled()) LOGGER.info("add File:" + curFileName); // copy Page reader = new PdfReader(curFileName); int newPages = PdfExtractEmptyPages.addTrimmedPages(curFileName, reader, writerNew, (PdfCopy) null, flgTrim); reader.close(); // update BookMark curBookMark.put("PAGE", new Integer(siteNr)); curBookMark.put("PAGES", new Integer(newPages)); siteNr += newPages; } documentNew.close(); writerNew.close(); }
From source file:de.mat.utils.pdftools.PdfSort4Print.java
License:Mozilla Public License
public static void sortPdfPages(String pdfSourceFile, String pdfDestinationFile, int perPage) throws Exception { PdfImportedPage page = null;/*from w w w . j a v a 2 s . c o m*/ if (perPage != 2 && perPage != 4) { throw new IllegalArgumentException( "Sorry, perPage must only be " + "2 or 4. All other is not implemented yet :-("); } // ####### // # fill to odd pagecount // ####### // create reader PdfReader readerOrig = new PdfReader(pdfSourceFile); // calc data int countPage = readerOrig.getNumberOfPages(); int blaetter = new Double(Math.ceil((countPage + 0.0) / perPage / 2)).intValue(); int zielPages = (blaetter * perPage * 2) - countPage; if (LOGGER.isInfoEnabled()) LOGGER.info("CurPages: " + countPage + " Blaetter:" + blaetter + " AddPage:" + zielPages); // add sites String oddFile = pdfDestinationFile + ".filled.pdf"; PdfStamper stamper = new PdfStamper(readerOrig, new FileOutputStream(oddFile)); // add empty pages for (int i = 1; i <= zielPages; i++) { if (LOGGER.isDebugEnabled()) LOGGER.debug("addEmptyPage: " + i); stamper.insertPage(readerOrig.getNumberOfPages() + 1, readerOrig.getPageSizeWithRotation(1)); } stamper.close(); readerOrig.close(); // ######## // # read new odd document and sort pages // ######## // step 1: create new reader PdfReader readerOdd = new PdfReader(oddFile); // create writerSorted String sortedFile = pdfDestinationFile; Document documentSorted = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerSorted = new PdfCopy(documentSorted, new FileOutputStream(sortedFile)); documentSorted.open(); // add pages in calced order List<Integer> lstPageNr = new ArrayList<Integer>(); int pageCount = readerOdd.getNumberOfPages(); int startseite = 1; for (int i = 1; i <= blaetter; i++) { if (perPage == 2) { startseite = ((i - 1) * perPage) + 1; if (LOGGER.isDebugEnabled()) LOGGER.debug("Blatt:" + i + " Startseite: " + startseite); // front top lstPageNr.add(new Integer(pageCount - startseite + 1)); // front bottom lstPageNr.add(new Integer(startseite)); // back top lstPageNr.add(new Integer(startseite + 1)); // back bottom lstPageNr.add(new Integer(pageCount - startseite + 1 - 1)); } else if (perPage == 4) { startseite = ((i - 1) * perPage) + 1; if (LOGGER.isDebugEnabled()) LOGGER.debug("Blatt:" + i + " Startseite: " + startseite); // front top left lstPageNr.add(new Integer(pageCount - startseite + 1)); // front top right lstPageNr.add(new Integer(startseite)); // front bottom lefts lstPageNr.add(new Integer(pageCount - startseite + 1 - 2)); // front bottom right lstPageNr.add(new Integer(startseite + 2)); // back top left lstPageNr.add(new Integer(startseite + 1)); // back top right lstPageNr.add(new Integer(pageCount - startseite + 1 - 1)); // back bottom left lstPageNr.add(new Integer(startseite + 1 + 2)); // back bottom right lstPageNr.add(new Integer(pageCount - startseite + 1 - 1 - 2)); } else { throw new IllegalArgumentException( "Sorry, perPage must " + "only be 2 or 4. All other is not implemented yet :-("); } } if (LOGGER.isInfoEnabled()) LOGGER.info("Seiten:" + lstPageNr.size()); // copy pages for (Iterator iter = lstPageNr.iterator(); iter.hasNext();) { int pageNum = ((Integer) iter.next()).intValue(); if (LOGGER.isDebugEnabled()) LOGGER.debug("addSortPage: " + pageNum); page = writerSorted.getImportedPage(readerOdd, pageNum); writerSorted.addPage(page); } // close everything documentSorted.close(); writerSorted.close(); readerOdd.close(); // delete Tmp-File File file = new File(oddFile); file.delete(); }