List of usage examples for com.lowagie.text.pdf PdfReader getPageSizeWithRotation
public Rectangle getPageSizeWithRotation(PdfDictionary page)
From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java
License:Open Source License
/** * Combine multiple protected PDF docs into one. * Note: this function may fail when creating large PDF files due to lack of available heap memory. To compensate, please configure the application server with more heap memory via -Xmx parameter. * * @sample/*from ww w. ja v a2 s. c o m*/ * pdf_blob_column = combineProtectedPDFDocuments(new Array(pdf_blob1,pdf_blob2,pdf_blob3), new Array(pdf_blob1_pass,pdf_blob2_pass,pdf_blob3_pass)); * * @param pdf_docs_bytearrays the array of documents to combine * @param pdf_docs_passwords an array of passwords to use */ public byte[] js_combineProtectedPDFDocuments(Object[] pdf_docs_bytearrays, Object[] pdf_docs_passwords) { if (pdf_docs_bytearrays == null || pdf_docs_bytearrays.length == 0) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; for (int f = 0; f < pdf_docs_bytearrays.length; f++) { if (!(pdf_docs_bytearrays[f] instanceof byte[])) continue; byte[] pdf_file = (byte[]) pdf_docs_bytearrays[f]; // we create a reader for a certain document byte[] password = null; if (pdf_docs_passwords != null && pdf_docs_passwords.length > f && pdf_docs_passwords[f] != null) { if (pdf_docs_passwords[f] instanceof String) password = pdf_docs_passwords[f].toString().getBytes(); } PdfReader reader = new PdfReader(pdf_file, password); reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += n; if (writer == null) { // step 1: creation of a document-object document = new Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, baos); // step 3: we open the document document.open(); } // step 4: we add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); } if (writer != null && document != null) { if (master.size() > 0) writer.setOutlines(master); // step 5: we close the document document.close(); } return baos.toByteArray(); } catch (Throwable e) { Debug.error(e); throw new RuntimeException("Error combinding pdf documents: " + e.getMessage(), e); //$NON-NLS-1$ } }
From source file:com.silverpeas.importExport.control.ImportExport.java
License:Open Source License
/** * @param userDetail/*from w ww . j a v a 2 s . c o m*/ * @param itemsToExport * @return * @throws ImportExportException */ public ExportPDFReport processExportPDF(UserDetail userDetail, List<WAAttributeValuePair> itemsToExport, NodePK rootPK) throws ImportExportException { ExportPDFReport report = new ExportPDFReport(); report.setDateDebut(new Date()); PublicationsTypeManager pubTypeManager = new PublicationsTypeManager(); String fileExportName = generateExportDirName(userDetail, "fusion"); String tempDir = FileRepositoryManager.getTemporaryPath(); File fileExportDir = new File(tempDir + fileExportName); if (!fileExportDir.exists()) { try { FileFolderManager.createFolder(fileExportDir); } catch (UtilException ex) { throw new ImportExportException("ImportExport", "importExport.EX_CANT_CREATE_FOLDER", ex); } } File pdfFileName = new File(tempDir + fileExportName + ".pdf"); try { // cration des rpertoires avec le nom des thmes et des publications List<AttachmentDetail> pdfList = pubTypeManager.processPDFExport(report, userDetail, itemsToExport, fileExportDir.getPath(), true, rootPK); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; if (!pdfList.isEmpty()) { boolean firstPage = true; for (AttachmentDetail attDetail : pdfList) { PdfReader reader = null; try { reader = new PdfReader( fileExportDir.getPath() + File.separatorChar + attDetail.getLogicalName()); } catch (IOException ioe) { // Attached file is not physically present on disk, ignore it and log event SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF", "CANT_FIND_PDF_FILE", "PDF file '" + attDetail.getLogicalName() + "' is not present on disk", ioe); } if (reader != null) { reader.consolidateNamedDestinations(); int nbPages = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += nbPages; if (firstPage) { document = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, new FileOutputStream(pdfFileName)); document.open(); firstPage = false; } for (int i = 1; i <= nbPages; i++) { try { PdfImportedPage page = writer.getImportedPage(reader, i); writer.addPage(page); } catch (Exception e) { // Can't import PDF file, ignore it and log event SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF", "CANT_MERGE_PDF_FILE", "PDF file is " + attDetail.getLogicalName(), e); } } PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } } } if (!master.isEmpty()) { writer.setOutlines(master); } writer.flush(); document.close(); } else { return null; } } catch (BadPdfFormatException e) { // Erreur lors de la copie throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } catch (DocumentException e) { // Impossible de copier le document throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } } catch (IOException e) { // Pb avec le rpertoire de destination throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } report.setPdfFileName(pdfFileName.getName()); report.setPdfFileSize(pdfFileName.length()); report.setPdfFilePath(FileServerUtils.getUrlToTempDir(pdfFileName.getName())); report.setDateFin(new Date()); return report; }
From source file:com.toolkit.util.pdf.HomeITextUserAgent.java
License:Open Source License
/** * Implementation Routine getImageResource. * @param uri String// w w w . j ava 2 s . co m * @return ImageResource * @see org.xhtmlrenderer.extend.UserAgentCallback#getImageResource(String) */ public ImageResource getImageResource(String uri) { ImageResource resource = null; uri = resolveURI(uri); resource = (ImageResource) _imageCache.get(uri); if (resource == null) { InputStream is = resolveAndOpenStream(uri); if (is != null) { try { URL url = new URL(uri); if (url.getPath() != null && url.getPath().toLowerCase().endsWith(".pdf")) { PdfReader reader = _outputDevice.getReader(url); PDFAsImage image = new PDFAsImage(url); Rectangle rect = reader.getPageSizeWithRotation(1); image.setInitialWidth(rect.width() * _outputDevice.getDotsPerPoint()); image.setInitialHeight(rect.height() * _outputDevice.getDotsPerPoint()); resource = new ImageResource(image); } else { Image image = Image.getInstance(url); scaleToOutputResolution(image); resource = new ImageResource(new ITextFSImage(image)); } _imageCache.put(uri, resource); } catch (IOException e) { XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e); } catch (BadElementException e) { XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e); } } } if (resource == null) { resource = new ImageResource(null); } return resource; }
From source file:edu.psu.citeseerx.web.ViewPDFPageController.java
License:Apache License
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException { String errorTitle = "Document Not Found"; String doi = request.getParameter("doi"); String rep = request.getParameter("rep"); String page = request.getParameter("page"); Map<String, Object> model = new HashMap<String, Object>(); if (doi == null || rep == null) { model.put("pagetitle", errorTitle); return new ModelAndView("viewDocError", model); }//from ww w . j a v a2 s .co m int iPage; try { iPage = Integer.parseInt(page); } catch (NumberFormatException e) { e.printStackTrace(); model.put("pagetitle", errorTitle); return new ModelAndView("viewDocError", model); } try { PdfReader reader = csxdao.getPdfReader(doi, rep); Document document = new Document(reader.getPageSizeWithRotation(iPage)); ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); PdfCopy copy = new PdfCopy(document, baos); document.open(); PdfImportedPage docPage = copy.getImportedPage(reader, iPage); copy.addPage(docPage); document.close(); response.setContentType("application/pdf"); response.setContentLength(baos.size()); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (IOException e) { e.printStackTrace(); model.put("pagetitle", errorTitle); return new ModelAndView("viewDocError", model); } catch (DocumentException e) { e.printStackTrace(); model.put("pagetitle", errorTitle); return new ModelAndView("viewDocError", model); } return null; }
From source file:Faculty.Scans_Upload_Processor.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {//from w ww. j a v a 2 s . c o m HttpSession session = request.getSession(); MyDB m = new MyDB(); int total_sheets = (Integer) session.getAttribute("total_sheets"); int p_id = (Integer) session.getAttribute("p_id"); String path = (String) getServletContext().getInitParameter("Directory") + "//"; if (!(new File(path)).exists()) { (new File(path)).mkdir(); // creates the directory if it does not exist } path = path + (Integer) p_id + "//"; System.out.println(); ArrayList err = new ArrayList(); ArrayList rollList = new ArrayList(); ArrayList DocIds = new ArrayList(); if (!(new File(path)).exists()) { (new File(path)).mkdir(); // creates the directory if it does not exist } boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded form items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { try { String str = item.getName(); String ext = FilenameUtils.getExtension(str); if (ext.equals("txt") || ext.equals("text")) { if ((new File(path + str)).exists()) { (new File(path + str)).delete(); // deletes the file if it does already exist } File savedFile = new File(path + str); item.write(savedFile); BufferedReader br = new BufferedReader(new FileReader(path + str)); String line; while ((line = br.readLine()) != null) { rollList.add(Integer.parseInt(line.trim())); } br.close(); DocIds = m.getDocIds(p_id, rollList); Iterator it = DocIds.iterator(); while (it.hasNext()) { int temp = (Integer) it.next(); if ((new File(path + temp + "//")).exists()) { try { delete(new File(path + temp + "//")); // deletes the directory if it does already exist } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } m.CreateDocIds(p_id, rollList); DocIds = m.getDocIds(p_id, rollList); it = DocIds.iterator(); while (it.hasNext()) { int temp = (Integer) it.next(); if (!(new File(path + temp + "//")).exists()) { (new File(path + temp + "//")).mkdir(); // creates the directory if it does not exist } } } else { // To Store Split Files if ((new File(path + "-1" + "//")).exists()) { try { delete(new File(path + "-1" + "//")); // deletes the directory if it does already exist } catch (IOException e) { e.printStackTrace(); System.exit(0); } } if (!(new File(path + "-1" + "//")).exists()) { (new File(path + "-1" + "//")).mkdir(); // creates the directory if it does not exist } //Splitting PDF int n = 0; // no.of pages try { File savedFile = new File(path + "-1" + "//" + str); item.write(savedFile); String inFile = path + "-1" + "//" + str; System.out.println("Reading " + inFile); PdfReader reader = new PdfReader(inFile); n = reader.getNumberOfPages(); // Reply User if PDF has invalid number of scans if (n != total_sheets * DocIds.size()) { m.deleteDocIds(p_id, rollList); Iterator it = DocIds.iterator(); while (it.hasNext()) { int temp = (Integer) it.next(); if ((new File(path + temp + "//")).exists()) { try { delete(new File(path + temp + "//")); // deletes the directory if it does already exist } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } err.add("PDF has missing scans!! It must have " + total_sheets * DocIds.size() + " pages"); break; } // postData(); System.out.println("Number of pages : " + n); int i = 0; while (i < n) { String outFile = (i + 1) + ".pdf"; System.out.println("Writing " + outFile); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, new FileOutputStream(path + "-1" + "//" + outFile)); document.open(); PdfImportedPage page = writer.getImportedPage(reader, ++i); writer.addPage(page); document.close(); writer.close(); } } catch (Exception e) { e.printStackTrace(); } // Placing files in Corresponding directories //System.out.println(DocIds); for (int i = 1; i <= n; i++) { int temp2 = (i - 1) / total_sheets; int d_id = (Integer) DocIds.get(temp2); String itemName = ""; if ((i % total_sheets) == 0) { itemName = ((Integer) total_sheets).toString(); } else { itemName = ((Integer) (i % total_sheets)).toString(); } File source = new File(path + "-1" + "//" + i + ".pdf"); File desc = new File( path + "-1//" + p_id + "_" + d_id + "_" + itemName + ".pdf"); try { FileUtils.copyFile(source, desc); uploadFile(path + "-1//" + p_id + "_" + d_id + "_" + itemName + ".pdf", (String) getServletContext().getInitParameter("UploadPhP")); } catch (IOException e) { e.printStackTrace(); } } try { delete(new File(path + "-1" + "//")); // deletes the directory if it does already exist delete(new File(path)); // deletes all docs in this paper id } catch (IOException e) { e.printStackTrace(); System.exit(0); } err.add("Scans sucessfully saved !"); } } catch (Exception e) { e.printStackTrace(); } } } request.setAttribute("err", err); RequestDispatcher rd = request.getRequestDispatcher("Paper_Spec_Fetcher"); rd.forward(request, response); } else { // Normal request. request.getParameter will suffice. } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:it.pdfsam.console.tools.pdf.PdfAlternateMix.java
License:Open Source License
/** * Execute the mix command. On error an exception is thrown. * @throws AlternateMixException/*from w w w.j av a 2s .c o m*/ */ public void execute() throws AlternateMixException { try { workingIndeterminate(); out_message = ""; Document pdf_document = null; PdfCopy pdf_writer = null; File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent()); PdfReader pdf_reader1; PdfReader pdf_reader2; pdf_reader1 = new PdfReader(new RandomAccessFileOrArray(input_file1.getAbsolutePath()), null); pdf_reader1.consolidateNamedDestinations(); limits1[1] = pdf_reader1.getNumberOfPages(); pdf_reader2 = new PdfReader(new RandomAccessFileOrArray(input_file2.getAbsolutePath()), null); pdf_reader2.consolidateNamedDestinations(); limits2[1] = pdf_reader2.getNumberOfPages(); pdf_document = new Document(pdf_reader1.getPageSizeWithRotation(1)); pdf_writer = new PdfCopy(pdf_document, new FileOutputStream(tmp_o_file)); if (compressed_boolean) { pdf_writer.setFullCompression(); } out_message += LogFormatter.formatMessage("Temporary file created-\n"); MainConsole.setDocumentCreator(pdf_document); pdf_document.open(); PdfImportedPage page; //importo boolean finished1 = false; boolean finished2 = false; int current1 = (reverseFirst) ? limits1[1] : limits1[0]; int current2 = (reverseSecond) ? limits2[1] : limits2[0]; while (!finished1 || !finished2) { if (!finished1) { if (current1 >= limits1[0] && current1 <= limits1[1]) { page = pdf_writer.getImportedPage(pdf_reader1, current1); pdf_writer.addPage(page); current1 = (reverseFirst) ? (current1 - 1) : (current1 + 1); } else { out_message += LogFormatter.formatMessage("First file processed-\n"); finished1 = true; } } if (!finished2) { if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) { page = pdf_writer.getImportedPage(pdf_reader2, current2); pdf_writer.addPage(page); current2 = (reverseSecond) ? (current2 - 1) : (current2 + 1); } else { out_message += LogFormatter.formatMessage("Second file processed-\n"); finished2 = true; } } } pdf_reader1.close(); pdf_writer.freeReader(pdf_reader1); pdf_reader2.close(); pdf_writer.freeReader(pdf_reader2); pdf_document.close(); // step 6: temporary buffer moved to output file renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); out_message += LogFormatter.formatMessage("Alternate mix completed-\n"); } catch (Exception e) { throw new AlternateMixException(e); } finally { workCompleted(); } }
From source file:it.pdfsam.console.tools.pdf.PdfConcat.java
License:Open Source License
/** * Execute the concat command. On error an exception is thrown. * @throws ConcatException/*from w w w . ja v a2 s .c o m*/ */ public void execute() throws ConcatException { try { percentageChanged(0, 0); out_message = ""; String file_name; int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; Document pdf_document = null; PdfConcatenator pdf_writer = null; int total_processed_pages = 0; String[] page_selection = u_string.split(":"); File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent()); PdfReader pdf_reader; for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) { String current_p_selection; //get page selection. If arrayoutofbounds default behaviour is "all" try { current_p_selection = page_selection[f].toLowerCase(); if (current_p_selection.equals("")) current_p_selection = "all"; } catch (Exception e) { current_p_selection = "all"; } //validation if (!(Pattern.compile("([0-9]+[-][0-9]+)|(all)", Pattern.CASE_INSENSITIVE) .matcher(current_p_selection).matches())) { String errorMsg = ""; try { tmp_o_file.delete(); } catch (Exception e) { errorMsg = " Unable to delete temporary file."; } throw new ConcatException( "ValidationError: Syntax error on " + current_p_selection + "." + errorMsg); } file_name = f_list_itr.next().toString(); //reader creation pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_name), null); pdf_reader.consolidateNamedDestinations(); int pdf_number_of_pages = pdf_reader.getNumberOfPages(); //default behaviour int start = 0; int end_page = pdf_number_of_pages; if (!(current_p_selection.equals("all"))) { boolean valid = true; String exceptionMsg = ""; String[] limits = current_p_selection.split("-"); try { start = Integer.parseInt(limits[0]); end_page = Integer.parseInt(limits[1]); } catch (Exception ex) { valid = false; exceptionMsg += "ValidationError: Syntax error on " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } if (valid) { //validation if (start < 0) { valid = false; exceptionMsg = "ValidationError: Syntax error. " + (start) + " must be positive in " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } else if (end_page > pdf_number_of_pages) { valid = false; exceptionMsg = "ValidationError: Cannot merge at page " + end_page + ". No such page."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } else if (start > end_page) { valid = false; exceptionMsg = "ValidationError: Syntax error. " + (start) + " is bigger than " + end_page + " in " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } } if (!valid) { throw new ConcatException(exceptionMsg); } } List bookmarks = SimpleBookmark.getBookmark(pdf_reader); if (bookmarks != null) { //if the end page is not the end of the doc, delete bookmarks after it if (end_page < pdf_number_of_pages) { SimpleBookmark.eliminatePages(bookmarks, new int[] { end_page + 1, pdf_number_of_pages }); } // if start page isn't the first page of the document, delete bookmarks before it if (start > 0) { SimpleBookmark.eliminatePages(bookmarks, new int[] { 1, start }); //bookmarks references must be taken back SimpleBookmark.shiftPageNumbers(bookmarks, -start, null); } if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += (end_page - start); out_message += LogFormatter.formatMessage(file_name + ": " + end_page + " pages-\n"); if (f == 0) { if (copyfields_boolean) { // step 1: we create a writer pdf_writer = new PdfCopyFieldsConcatenator(new FileOutputStream(tmp_o_file), compressed_boolean); HashMap meta = pdf_reader.getInfo(); meta.put("Creator", MainConsole.CREATOR); } else { // step 1: creation of a document-object pdf_document = new Document(pdf_reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document pdf_writer = new PdfSimpleConcatenator(pdf_document, new FileOutputStream(tmp_o_file), compressed_boolean); // step 3: we open the document MainConsole.setDocumentCreator(pdf_document); pdf_document.open(); } out_message += LogFormatter.formatMessage("Temporary file created-\n"); } // step 4: we add content pdf_reader.selectPages(start + "-" + end_page); pdf_writer.addDocument(pdf_reader); //fix 03/07 //pdf_reader = null; pdf_reader.close(); pdf_writer.freeReader(pdf_reader); total_processed_pages += end_page - start + 1; out_message += LogFormatter.formatMessage((end_page - start) + " pages processed correctly-\n"); f++; try { percentageChanged((f * 100) / f_list.size(), (end_page - start)); } catch (RuntimeException re) { out_message += LogFormatter.formatMessage("RuntimeException: " + re.getMessage() + "\n"); } } if (master.size() > 0) { pdf_writer.setOutlines(master); } out_message += LogFormatter.formatMessage("Total processed pages: " + total_processed_pages + "-\n"); // step 5: we close the document if (pdf_document != null) { pdf_document.close(); } pdf_writer.close(); // step 6: temporary buffer moved to output file renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); } catch (Exception e) { throw new ConcatException(e); } finally { workCompleted(); } }
From source file:it.pdfsam.console.tools.pdf.PdfSplit.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_ODD or S_EVEN * @param pdf_reader pdfreader of the original pdf document * @throws Exception//from w w w . j a va2 s.c o m */ private void doSplitOddEven(PdfReader pdf_reader) throws Exception { int current_page; Document current_document = new Document(pdf_reader.getPageSizeWithRotation(1)); boolean time_to_close = false; PdfCopy pdf_writer = null; PdfImportedPage imported_page; File tmp_o_file = null; File o_file = null; for (current_page = 1; current_page <= n; current_page++) { //check if i've to read one more page or to open a new doc if ((current_page != 1) && ((split_type.equals(CmdParser.S_ODD) && ((current_page % 2) != 0)) || (split_type.equals(CmdParser.S_EVEN) && ((current_page % 2) == 0)))) { time_to_close = true; } else { time_to_close = false; } if (!time_to_close) { tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir); o_file = new File(o_dir, prefixParser.generateFileName(file_number_formatter.format(current_page))); // step 1: creation of a document-object current_document = new Document(pdf_reader.getPageSizeWithRotation(current_page)); // step 2: we create a writer that listens to the document pdf_writer = new PdfCopy(current_document, new FileOutputStream(tmp_o_file)); if (compressed_boolean) { pdf_writer.setFullCompression(); } MainConsole.setDocumentCreator(current_document); // step 3: we open the document current_document.open(); } imported_page = pdf_writer.getImportedPage(pdf_reader, current_page); pdf_writer.addPage(imported_page); //if it's time to close the document if ((time_to_close) || (current_page == n) || ((current_page == 1) && (split_type.equals(CmdParser.S_ODD)))) { current_document.close(); renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); } percentageChanged(java.lang.Math.round((current_page * 100) / n)); } out_message += LogFormatter.formatMessage("Split " + split_type + " done.\n"); }
From source file:it.pdfsam.console.tools.pdf.PdfSplit.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_BURST * @param pdf_reader pdfreader of the original pdf document * @throws Exception/*w ww . jav a2 s .c o m*/ */ private void doSplitBurst(PdfReader pdf_reader) throws Exception { int current_page; Document current_document; for (current_page = 1; current_page <= n; current_page++) { File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir); File o_file = new File(o_dir, prefixParser.generateFileName(file_number_formatter.format(current_page))); // step 1: creation of a document-object current_document = new Document(pdf_reader.getPageSizeWithRotation(current_page)); // step 2: we create a writer that listens to the document PdfCopy pdf_writer = new PdfCopy(current_document, new FileOutputStream(tmp_o_file)); if (compressed_boolean) { pdf_writer.setFullCompression(); } // step 3: we open the document MainConsole.setDocumentCreator(current_document); current_document.open(); PdfImportedPage imported_page = pdf_writer.getImportedPage(pdf_reader, current_page); pdf_writer.addPage(imported_page); current_document.close(); renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); percentageChanged(java.lang.Math.round((current_page * 100) / n)); } out_message += LogFormatter.formatMessage("Burst done.\n"); }
From source file:it.pdfsam.console.tools.pdf.PdfSplit.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_SPLIT * //from w ww. ja v a 2s . c om * @param pdf_reader * pdfreader of the original pdf document * @param out_files_name * output file name * @throws Exception */ private void doSplitSplit(PdfReader pdf_reader) throws Exception { String[] limits = snumber_page.split("-"); Arrays.sort(limits, new StrNumComparator()); // limits list validation end clean LinkedList limits_list = validateSplitLimits(limits, n); if (limits_list == null) { throw new SplitException("PageNumberError: Cannot find page limits, please check input value."); } if (limits_list.isEmpty()) { throw new SplitException("PageNumberError: Cannot find page limits, please check input value."); } // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START // BOOKMARKS Iterator itr = limits_list.iterator(); int current_page; int relative_current_page = 0; int end_page = n; int start_page = 1; Document current_document = new Document(pdf_reader.getPageSizeWithRotation(1)); PdfCopy pdf_writer = null; PdfImportedPage imported_page; File tmp_o_file = null; File o_file = null; if (itr.hasNext()) { end_page = Integer.parseInt((String) itr.next()); } for (current_page = 1; current_page <= n; current_page++) { relative_current_page++; //check if i've to read one more page or to open a new doc if (relative_current_page == 1) { tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir); o_file = new File(o_dir, prefixParser.generateFileName(file_number_formatter.format(current_page))); start_page = current_page; // step 1: creation of a document-object current_document = new Document(pdf_reader.getPageSizeWithRotation(current_page)); // step 2: we create a writer that listens to the document pdf_writer = new PdfCopy(current_document, new FileOutputStream(tmp_o_file)); if (compressed_boolean) { pdf_writer.setFullCompression(); } MainConsole.setDocumentCreator(current_document); // step 3: we open the document current_document.open(); } imported_page = pdf_writer.getImportedPage(pdf_reader, current_page); pdf_writer.addPage(imported_page); // if it's time to close the document if (current_page == end_page) { out_message += LogFormatter.formatMessage( "Temporary document " + tmp_o_file.getName() + " done, now adding bookmarks...\n"); //manage bookmarks ArrayList master = new ArrayList(); List this_book = SimpleBookmark.getBookmark(pdf_reader); if (this_book != null) { //ArrayList this_book = new ArrayList(bookmarks); SimpleBookmark.eliminatePages(this_book, new int[] { end_page + 1, n }); if (start_page > 1) { SimpleBookmark.eliminatePages(this_book, new int[] { 1, start_page - 1 }); SimpleBookmark.shiftPageNumbers(this_book, -(start_page - 1), null); } master.addAll(this_book); pdf_writer.setOutlines(master); } relative_current_page = 0; current_document.close(); renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); end_page = (itr.hasNext()) ? Integer.parseInt((String) itr.next()) : n; } percentageChanged((current_page * 100) / n); } out_message += LogFormatter.formatMessage("Split " + split_type + " done.\n"); }