List of usage examples for com.lowagie.text.pdf PdfCopy close
public void close()
Document
was closed and that no other Elements
will be added. 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 {/*ww w. java 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:jPDFmelange.MelangeJFrame.java
License:Open Source License
/** * Main save method./*from w ww .j a va2 s .c o m*/ * <p> * Saves all elements of the main list represented with its {@link MelangeJFrame#listContentMain content} * to the specified file. * * @param fileName name of file to save. * @throws IOException on File IO error. * @throws DocumentException on itext PDF error. */ private void saveFile(String fileName) throws IOException, DocumentException { File file = new File(fileName); File tmpfile = File.createTempFile("Mixer", null, file.getParentFile()); String bakFileName = fileName.substring(0, fileName.lastIndexOf('.')).concat(".bak"); File bakfile = new File(bakFileName); // // prevent writing to a PDF that is blocked by the renderer. // jPanePreview.closePdfFile(); // itext usage System.out.println("Writing new content to <" + tmpfile.getName() + ">"); PdfReader reader = null; PdfDictionary dict = null; Document pdfDoc = new Document(); PdfCopy writer = new PdfCopy(pdfDoc, new FileOutputStream(tmpfile)); pdfDoc.open(); PageNode node = null; for (int i = 0; i < listContentMain.size(); i++) { node = (PageNode) listContentMain.get(i); if (node.password == null) reader = new PdfReader(node.filename); else reader = new PdfReader(node.filename, node.password.getBytes()); dict = reader.getPageN(node.pagenumber); dict.put(PdfName.ROTATE, new PdfNumber(node.rotation)); writer.addPage(writer.getImportedPage(reader, node.pagenumber)); reader.close(); // close input file System.out .println("Page " + node.pagenumber + " File:" + node.filename + " Rotation:" + node.rotation); } // // save page mode and layout preferences // if (jCheckBoxEnablePDFViewerPrefs.isSelected()) { String key = jPanelViewPrefs.getKeyPageMode(); writer.setViewerPreferences(PageMode.get(key)); key = jPanelViewPrefs.getKeyPageLayout(); writer.setViewerPreferences(PageLayout.get(key)); if (jPanelViewPrefs.jCheckBoxHideToolbar.isSelected()) writer.addViewerPreference(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE); if (jPanelViewPrefs.jCheckBoxHideMenubar.isSelected()) writer.addViewerPreference(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE); if (jPanelViewPrefs.jCheckBoxHideWindowUI.isSelected()) writer.addViewerPreference(PdfName.HIDEWINDOWUI, PdfBoolean.PDFTRUE); if (jPanelViewPrefs.jCheckBoxFitWindow.isSelected()) writer.addViewerPreference(PdfName.FITWINDOW, PdfBoolean.PDFTRUE); if (jPanelViewPrefs.jCheckBoxCenterWindow.isSelected()) writer.addViewerPreference(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE); if (jPanelViewPrefs.jCheckBoxDisplayDocTitle.isSelected()) writer.addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE); } pdfDoc.close(); // close Helper Class writer.close(); // close output file // save old file to a XXX.bak file if (bakfile.exists()) bakfile.delete(); if (file.renameTo(bakfile.getCanonicalFile())) { System.out.println("Orginal File is saved in <" + bakfile.getName() + ">"); } // move new content to original file name file = new File(fileName); if (tmpfile.renameTo(file)) System.out.println("<" + tmpfile.getName() + "> is copied to <" + file.getName() + "> "); else { JOptionPane.showMessageDialog(MelangeJFrame.this, messages.getString("canNotWriteFile") + file.getName() + messages.getString("trySaveAs"), messages.getString("warning"), JOptionPane.WARNING_MESSAGE); System.out.println( messages.getString("canNotWriteFile") + file.getName() + messages.getString("trySaveAs")); } }
From source file:org.jrimum.bopepo.pdf.PDFs.java
License:Apache License
/** * Junta varios arquivos pdf em um s./*from ww w .java2 s . c om*/ * * @param pdfFiles * Coleo de array de bytes * @param info * Usa somente as informaes * (title,subject,keywords,author,creator) * * @return Arquivo PDF em forma de byte * * @since 0.2 */ public static byte[] mergeFiles(Collection<byte[]> pdfFiles, PdfDocInfo info) { try { ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); Document document = new Document(); PdfCopy copy = new PdfCopy(document, byteOS); document.open(); for (byte[] f : pdfFiles) { PdfReader reader = new PdfReader(f); for (int page = 1; page <= reader.getNumberOfPages(); page++) { copy.addPage(copy.getImportedPage(reader, page)); } reader.close(); } document.addCreationDate(); if (info != null) { document.addAuthor(info.author()); document.addCreator(info.creator()); document.addTitle(info.title()); document.addSubject(info.subject()); document.addKeywords(info.keywords()); } copy.close(); document.close(); byteOS.close(); return byteOS.toByteArray(); } catch (Exception e) { return Exceptions.throwIllegalStateException(e); } }