List of usage examples for com.itextpdf.text.pdf PdfCopy PdfCopy
public PdfCopy(Document document, OutputStream os) throws DocumentException
From source file:Separator.java
License:Apache License
public static void splitPDFFile(String fileName) { // splitting "documents" up by consecutive orientations try {//from w ww . j av a 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:Separator.java
License:Apache License
public static void crop(String inFileName, String outFileName, int split, boolean vert) throws Exception { PdfReader reader = new PdfReader(new File(inFileName).getAbsolutePath()); String PDFName = outFileName.substring(outFileName.lastIndexOf("Folder\\") + 7, outFileName.indexOf(".pdf")); File fn = new File(scanFolder + PDFName + "\\" + PDFName + "_split_" + split + ".pdf"); fn.getParentFile().mkdirs();/* w w w.ja va 2 s. c o m*/ int count = reader.getNumberOfPages(); Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, new FileOutputStream(fn.getAbsolutePath())); doc.open(); if (vert) { for (int i = 1; i <= count; i++) { reader.getPageN(i).put(PdfName.CROPBOX, new PdfRectangle(PageSize.LETTER)); copy.addPage(copy.getImportedPage(reader, i)); } } else { if (!doubSided) { for (int j = 1; j <= count; j++) { reader.getPageN(j).put(PdfName.CROPBOX, new PdfRectangle((new Rectangle(0, 180, 792, 792)))); PdfDictionary pageDict; int rot = reader.getPageRotation(j); pageDict = reader.getPageN(j); pageDict.put(PdfName.ROTATE, new PdfNumber(rot + 90)); copy.addPage(copy.getImportedPage(reader, j)); } } else { for (int j = 1; j <= count; j++) { reader.getPageN(j).put(PdfName.CROPBOX, new PdfRectangle(new Rectangle(0, 180, 792, 792))); PdfDictionary pageDict; pageDict = reader.getPageN(j); if (j % 2 == 0) { // even pageDict.put(PdfName.ROTATE, new PdfNumber(270)); } else { // odd pageDict.put(PdfName.ROTATE, new PdfNumber(90)); } copy.addPage(copy.getImportedPage(reader, j)); } } } doc.close(); }
From source file:adams.flow.transformer.PDFExtract.java
License:Open Source License
/** * Executes the flow item./*from w w w. ja v a2s .c om*/ * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; File file; int i; Document document; PdfCopy copy; PdfReader reader; int[] pages; int page; FileOutputStream fos; result = null; // get file if (m_InputToken.getPayload() instanceof File) file = (File) m_InputToken.getPayload(); else file = new PlaceholderFile((String) m_InputToken.getPayload()); fos = null; try { if (isLoggingEnabled()) getLogger().info("Extracting pages from '" + file + "' into '" + m_Output + "'"); document = new Document(); fos = new FileOutputStream(m_Output.getAbsolutePath()); copy = new PdfCopy(document, fos); document.open(); document.addCreationDate(); document.addCreator(Environment.getInstance().getProject()); document.addAuthor(System.getProperty("user.name")); reader = new PdfReader(file.getAbsolutePath()); if (isLoggingEnabled()) getLogger().info("- #pages: " + reader.getNumberOfPages()); m_Pages.setMax(reader.getNumberOfPages()); pages = m_Pages.getIntIndices(); for (i = 0; i < pages.length; i++) { page = pages[i] + 1; copy.addPage(copy.getImportedPage(reader, page)); if (isLoggingEnabled()) getLogger().info("- adding page: " + page); } copy.freeReader(reader); document.close(); } catch (Exception e) { result = handleException("Failed to extract pages: ", e); } finally { FileUtils.closeQuietly(fos); } if (result == null) m_OutputToken = new Token(m_Output.getAbsolutePath()); return result; }
From source file:adams.flow.transformer.PDFMerge.java
License:Open Source License
/** * Executes the flow item./*from w w w. ja va2s. c om*/ * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; PlaceholderFile[] files; int i; int n; int pages; Document document; PdfCopy copy; PdfReader reader; FileOutputStream fos; result = null; // get files files = FileUtils.toPlaceholderFileArray(m_InputToken.getPayload()); fos = null; try { if (isLoggingEnabled()) getLogger().info("Merging PDFs into: " + m_Output); document = new Document(); fos = new FileOutputStream(m_Output.getAbsolutePath()); copy = new PdfCopy(document, fos); document.open(); document.addCreationDate(); document.addCreator(Environment.getInstance().getProject()); document.addAuthor(System.getProperty("user.name")); for (i = 0; i < files.length; i++) { if (isLoggingEnabled()) getLogger().info("Adding file: " + files[i]); reader = new PdfReader(files[i].getAbsolutePath()); // loop over the pages in that document pages = reader.getNumberOfPages(); if (isLoggingEnabled()) getLogger().info("- #pages: " + pages); for (n = 1; n <= pages; n++) { copy.addPage(copy.getImportedPage(reader, n)); if (isLoggingEnabled()) getLogger().info("- adding page: " + n); } copy.freeReader(reader); } document.close(); } catch (Exception e) { result = handleException("Failed to merge PDF files: ", e); } finally { FileUtils.closeQuietly(fos); } if (result == null) m_OutputToken = new Token(m_Output.getAbsolutePath()); return result; }
From source file:be.rheynaerde.pufmanager.gui.workers.ExportFullPdfWorker.java
License:Open Source License
@Override protected byte[] doInBackground() throws Exception { ByteArrayOutputStream largeBaos = new ByteArrayOutputStream(); Document document = new Document(); PdfCopy copy = new PdfCopy(document, largeBaos); document.open();// w w w. j a v a 2 s .c o m String stampText = ResourceBundle .getBundle("be.rheynaerde.pufmanager.gui.export", competition.getSettings().getLocale()) .getString("ExportFullPdf.poolsheet.stamp"); for (int i = 0; i < competition.getRoundCount(); i++) { publish(i); Round round = competition.getRound(i); int piste = 1; for (Match match : round.getMatches()) { final Match currentMatch = match; ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (match.getRound().includeInternalBouts()) { PufCompletePoolSheetConfiguration config = new NamedPufCompletePoolSheetConfiguration( match.getFirstTeam().getFencerNames(), match.getSecondTeam().getFencerNames(), 20f, competition.getSettings().getImage(), competition.getSettings().getLocale(), competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) { @Override public String getResult(int team1, int player1, int team2, int player2) { Fencer player = (team1 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player1); Fencer opponent = (team2 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player2); PoolResult result = competition.getCompetitionPool().getResult(player, opponent); return result == null ? null : result.toString(); } }; PufCompletePoolSheet sheet = new PufCompletePoolSheet(config); sheet.export(baos); } else { PufTeamPoolSheetConfiguration config = new NamedPufTeamPoolSheetConfiguration( match.getFirstTeam().getFencerNames(), match.getSecondTeam().getFencerNames(), 20f, competition.getSettings().getImage(), competition.getSettings().getLocale(), competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) { @Override public String getResult(int team1, int player1, int team2, int player2) { Fencer player = (team1 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player1); Fencer opponent = (team2 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player2); PoolResult result = competition.getCompetitionPool().getResult(player, opponent); return result == null ? null : result.toString(); } }; PufTeamPoolSheet sheet = new PufTeamPoolSheet(config); sheet.export(baos); } addPdfToDocument(baos, copy, String.format(stampText, i + 1, piste)); piste++; } if (i == 0) { for (Team team : round.getRestingTeams()) { final Team currentTeam = team; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PufSingleTeamPoolSheetConfiguration config = new NamedPufSingleTeamPoolSheetConfiguration( team.getFencerNames(), 20f, competition.getSettings().getImage(), competition.getSettings().getLocale(), competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) { @Override public String getResult(int player, int opponent) { Fencer playerFencer = currentTeam.getFencer(player); Fencer opponentFencer = currentTeam.getFencer(opponent); PoolResult result = competition.getCompetitionPool().getResult(playerFencer, opponentFencer); return result == null ? null : result.toString(); } }; PufSingleTeamPoolSheet sheet = new PufSingleTeamPoolSheet(config); sheet.export(baos); addPdfToDocument(baos, copy, String.format(stampText, i + 1, piste)); piste++; } } } document.close(); publish(competition.getRoundCount()); return largeBaos.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.ja 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.docdoku.server.extras.TitleBlockGenerator.java
License:Open Source License
public static InputStream mergePdfDocuments(InputStream input1, InputStream input2) { try {/*from w w w.j a v a2s .c om*/ File tmpDir = com.google.common.io.Files.createTempDir(); File tmpCopyFile = new File(tmpDir, TEMP_FILE_NAME); InputStream[] files = { input1, input2 }; Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, new FileOutputStream(tmpCopyFile)); doc.open(); PdfReader pdfReader; int n; // TODO check for resources to be closed for (InputStream file : files) { pdfReader = new PdfReader(file); n = pdfReader.getNumberOfPages(); for (int page = 0; page < n;) { copy.addPage(copy.getImportedPage(pdfReader, ++page)); } } doc.close(); tmpDir.deleteOnExit(); return new FileInputStream(tmpCopyFile); } catch (Exception e) { LOGGER.log(Level.INFO, null, e); } return null; }
From source file:com.github.sgelb.sldownloader.model.Pdf.java
License:Open Source License
public void mergePdfs() throws DocumentException, IOException { String title = book.getPdfTitle() + ".pdf"; File saveFile = new File(saveFolder, title); int count = 1; while (saveFile.exists()) { title = book.getPdfTitle() + "_" + count++ + ".pdf"; saveFile = new File(saveFolder, title); }//from w ww . ja va 2 s . c o m book.setInfo("saveFile", saveFile.toString()); Document document = new Document(); PdfCopy destPdf = new PdfCopy(document, new FileOutputStream(saveFile)); document.open(); PdfReader reader; int page_offset = 0; int n; ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>(); List<HashMap<String, Object>> tmp; count = 1; System.out.println("Start mergin\u2026"); for (File srcPdf : src) { if (Thread.interrupted()) { return; } System.out.print(":: " + count++ + "/" + src.size()); reader = new PdfReader(srcPdf.toString()); tmp = SimpleBookmark.getBookmark(reader); if (tmp != null) { SimpleBookmark.shiftPageNumbers(tmp, page_offset, null); bookmarks.addAll(tmp); } n = reader.getNumberOfPages(); page_offset += n; for (int page = 0; page < n;) { destPdf.addPage(destPdf.getImportedPage(reader, ++page)); } destPdf.freeReader(reader); reader.close(); System.out.println(" succeed."); } if (!bookmarks.isEmpty()) { destPdf.setOutlines(bookmarks); } if (book.getInfo("author") != null) document.addAuthor(book.getInfo("author")); if (book.getInfo("title") != null) document.addTitle(book.getInfo("title")); if (book.getInfo("subtitle") != null) document.addSubject(book.getInfo("subtitle")); document.close(); System.out.println("Merge complete. Saved to " + saveFile); }
From source file:com.innoq.iQpdfutil.Main.java
License:Open Source License
/** * This method produces a new pdf that is written to the output stream. * * <p>//ww w .j a v a 2 s. c o m * The newly created pdf contains all the pages of all the provided * input pdf files in the right order. Where necessary empty pages * ensure that the pages of every input pdf begin on an odd page. * </p> * */ public static void concatPDFs(Readers readers, OutputStream os) throws DocumentException, IOException { Document document = new Document(); PdfCopy copy = new PdfCopy(document, os); document.open(); for (PdfReader reader : readers) { copyPages(reader, copy); } document.close(); }
From source file:com.photon.phresco.framework.docs.impl.DocConvertor.java
License:Apache License
/** * @param fileUrl//from ww w . ja v a 2 s .c om * @return * @throws FileNotFoundException * @throws IOException * @throws DocumentException */ private static PdfInput convertPdf(String fileUrl) throws IOException, DocumentException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method DocConvertor.convertPdf(String fileUrl)"); } PdfReader reader = new PdfReader(new FileInputStream(fileUrl)); int numberOfPages = reader.getNumberOfPages(); Document doc = new Document(); ByteArrayOutputStream os = new ByteArrayOutputStream(); PdfCopy copy = new PdfCopy(doc, os); doc.open(); //page number in PDF starts at 1 for (int i = 1; i <= numberOfPages; i++) { copy.addPage(copy.getImportedPage(reader, i)); } doc.close(); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); os.close(); PdfInput input = new PdfInput(); input.setInputStream(new FileInputStream(fileUrl)); return input; }