List of usage examples for com.lowagie.text Document addCreator
public boolean addCreator(String creator)
From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_BLEVEL * /*w w w .j ava 2 s . c om*/ * @param inputCommand * @param bookmarksTable * bookmarks table. It's populated only when splitting by bookmarks. If null or empty it's ignored * @throws Exception */ private void executeSplit(SplitParsedCommand inputCommand, Hashtable bookmarksTable) throws Exception { pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); int n = pdfReader.getNumberOfPages(); BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n); int fileNum = 0; LOG.info("Found " + n + " pages in input pdf document."); Integer[] limits = inputCommand.getSplitPageNumbers(); // limits list validation end clean TreeSet limitsList = validateSplitLimits(limits, n); if (limitsList.isEmpty()) { throw new SplitException(SplitException.ERR_NO_PAGE_LIMITS); } // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START BOOKMARKS int currentPage; Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1)); int relativeCurrentPage = 0; int endPage = n; int startPage = 1; PdfImportedPage importedPage; File tmpFile = null; File outFile = null; Iterator itr = limitsList.iterator(); if (itr.hasNext()) { endPage = ((Integer) itr.next()).intValue(); } for (currentPage = 1; currentPage <= n; currentPage++) { relativeCurrentPage++; // check if i've to read one more page or to open a new doc if (relativeCurrentPage == 1) { LOG.debug("Creating a new document."); fileNum++; tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); String bookmark = null; if (bookmarksTable != null && bookmarksTable.size() > 0) { bookmark = (String) bookmarksTable.get(new Integer(currentPage)); } FileNameRequest request = new FileNameRequest(currentPage, fileNum, bookmark); outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request)); startPage = currentPage; currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage)); pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile)); // set creator currentDocument.addCreator(ConsoleServicesFacade.CREATOR); setCompressionSettingOnWriter(inputCommand, pdfWriter); setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion())); currentDocument.open(); } importedPage = pdfWriter.getImportedPage(pdfReader, currentPage); pdfWriter.addPage(importedPage); // if it's time to close the document if (currentPage == endPage) { LOG.info("Temporary document " + tmpFile.getName() + " done, now adding bookmarks..."); // manage bookmarks List bookmarks = bookmarkProcessor.processBookmarks(startPage, endPage); if (bookmarks != null) { pdfWriter.setOutlines(bookmarks); } relativeCurrentPage = 0; currentDocument.close(); FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite()); LOG.debug("File " + outFile.getCanonicalPath() + " created."); endPage = (itr.hasNext()) ? ((Integer) itr.next()).intValue() : n; } setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n); } pdfReader.close(); LOG.info("Split " + inputCommand.getSplitType() + " done."); }
From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_SIZE * //w w w .j av a 2 s .c o m * @param inputCommand * @throws Exception */ private void executeSizeSplit(SplitParsedCommand inputCommand) throws Exception { pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); int n = pdfReader.getNumberOfPages(); BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n); int fileNum = 0; LOG.info("Found " + n + " pages in input pdf document."); int currentPage; Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1)); PdfImportedPage importedPage; File tmpFile = null; File outFile = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int startPage = 0; int relativeCurrentPage = 0; for (currentPage = 1; currentPage <= n; currentPage++) { relativeCurrentPage++; // time to open a new document? if (relativeCurrentPage == 1) { LOG.debug("Creating a new document."); startPage = currentPage; fileNum++; tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); FileNameRequest request = new FileNameRequest(currentPage, fileNum, null); outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request)); currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage)); baos = new ByteArrayOutputStream(); pdfWriter = new PdfSmartCopy(currentDocument, baos); // set creator currentDocument.addCreator(ConsoleServicesFacade.CREATOR); setCompressionSettingOnWriter(inputCommand, pdfWriter); setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion())); currentDocument.open(); } importedPage = pdfWriter.getImportedPage(pdfReader, currentPage); pdfWriter.addPage(importedPage); // if it's time to close the document if ((currentPage == n) || ((relativeCurrentPage > 1) && ((baos.size() / relativeCurrentPage) * (1 + relativeCurrentPage) > inputCommand.getSplitSize().longValue()))) { LOG.debug("Current stream size: " + baos.size() + " bytes."); // manage bookmarks List bookmarks = bookmarkProcessor.processBookmarks(startPage, currentPage); if (bookmarks != null) { pdfWriter.setOutlines(bookmarks); } relativeCurrentPage = 0; currentDocument.close(); FileOutputStream fos = new FileOutputStream(tmpFile); baos.writeTo(fos); fos.close(); baos.close(); LOG.info("Temporary document " + tmpFile.getName() + " done."); FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite()); LOG.debug("File " + outFile.getCanonicalPath() + " created."); } setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n); } pdfReader.close(); LOG.info("Split " + inputCommand.getSplitType() + " done."); }
From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java
License:Open Source License
/** * Create PDF//w ww . ja va 2s . co m * * @param name * Filename * @param selection * Selected Nodes * @param dm * DataModel * @param pl * ProgressListener */ @SuppressWarnings("unchecked") public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) { com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50); try { ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection); if (charts.size() > 0) { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name)); writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); document.addAuthor("Jrg Werner"); document.addSubject("Created by JCombinations"); document.addKeywords("JCombinations"); document.addCreator("JCombinations using iText"); // we define a header and a footer HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false); HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase(".")); footer.setAlignment(Element.ALIGN_CENTER); document.setHeader(header); document.setFooter(footer); document.open(); DefaultFontMapper mapper = new DefaultFontMapper(); FontFactory.registerDirectories(); mapper.insertDirectory("c:\\WINNT\\fonts"); PdfContentByte cb = writer.getDirectContent(); pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size())); for (int i = 0; i < charts.size(); i++) { ExtendedJFreeChart chart = charts.get(i); PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN), document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN)); Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN), document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper); Rectangle2D r2d = new Rectangle2D.Double(0, 0, document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN), document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN)); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN)); PdfDestination destination = new PdfDestination(PdfDestination.FIT); TreePath treePath = chart.getTreePath(); PdfOutline po = cb.getRootOutline(); for (int j = 0; j < treePath.getPathCount(); j++) { ArrayList<PdfOutline> lpo = po.getKids(); PdfOutline cpo = null; for (PdfOutline outline : lpo) if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0) cpo = outline; if (cpo == null) cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString()); po = cpo; } document.newPage(); pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i)); } document.close(); pl.progressEnded(new ProgressEvent(GridChartPanel.class)); } } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } }
From source file:oscar.eform.util.EFormPDFServlet.java
License:Open Source License
private void addDocumentProps(Document document, String title, Properties props) { document.addTitle(title);// w ww. j a va2 s.co m document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size final String PAGESIZE = "printPageSize"; Rectangle pageSize = PageSize.LETTER; if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) pageSize = PageSize.HALFLETTER; if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) pageSize = PageSize.A6; document.setPageSize(pageSize); document.open(); }
From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java
License:Open Source License
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx) throws DocumentException { logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); // added by vic, hsfo Enumeration<String> em = req.getParameterNames(); while (em.hasMoreElements()) { logger.debug("para=" + em.nextElement()); }/* w w w.ja v a 2 s . co m*/ em = req.getAttributeNames(); while (em.hasMoreElements()) logger.debug("attr: " + em.nextElement()); if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) { return generateHsfoRxPDF(req); } String newline = System.getProperty("line.separator"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null; String method = req.getParameter("__method"); String origPrintDate = null; String numPrint = null; if (method != null && method.equalsIgnoreCase("rePrint")) { origPrintDate = req.getParameter("origPrintDate"); numPrint = req.getParameter("numPrints"); } logger.debug("method in generatePDFDocumentBytes " + method); String clinicName; String clinicTel; String clinicFax; // check if satellite clinic is used String useSatelliteClinic = req.getParameter("useSC"); logger.debug(useSatelliteClinic); if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) { String scAddress = req.getParameter("scAddress"); logger.debug("clinic detail" + "=" + scAddress); HashMap<String, String> hm = parseSCAddress(scAddress); clinicName = hm.get("clinicName"); clinicTel = hm.get("clinicTel"); clinicFax = hm.get("clinicFax"); } else { // parameters need to be passed to header and footer clinicName = req.getParameter("clinicName"); logger.debug("clinicName" + "=" + clinicName); clinicTel = req.getParameter("clinicPhone"); clinicFax = req.getParameter("clinicFax"); } String patientPhone = req.getParameter("patientPhone"); String patientCityPostal = req.getParameter("patientCityPostal"); String patientAddress = req.getParameter("patientAddress"); String patientName = req.getParameter("patientName"); String sigDoctorName = req.getParameter("sigDoctorName"); String rxDate = req.getParameter("rxDate"); String rx = req.getParameter("rx"); String patientDOB = req.getParameter("patientDOB"); String showPatientDOB = req.getParameter("showPatientDOB"); String imgFile = req.getParameter("imgFile"); String patientHIN = req.getParameter("patientHIN"); String patientChartNo = req.getParameter("patientChartNo"); String pracNo = req.getParameter("pracNo"); Locale locale = req.getLocale(); boolean isShowDemoDOB = false; if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) { isShowDemoDOB = true; } if (!isShowDemoDOB) patientDOB = ""; if (rx == null) { rx = ""; } String additNotes = req.getParameter("additNotes"); String[] rxA = rx.split(newline); List<String> listRx = new ArrayList<String>(); String listElem = ""; // parse rx and put into a list of rx; for (String s : rxA) { if (s.equals("") || s.equals(newline) || s.length() == 1) { listRx.add(listElem); listElem = ""; } else { listElem = listElem + s; listElem += newline; } } // get the print prop values Properties props = new Properties(); StringBuilder temp = new StringBuilder(); for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getParameter(temp.toString())); } for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString()); } Document document = new Document(); try { String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown"; // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages // however the same graphic will be applied to all pages // ie. __graphicPage=2&__graphicPage=3 String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile"); int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length; if (cfgGraphicFile != null) { // for (String s : cfgGraphicFile) { // p("cfgGraphicFile", s); // } } String[] graphicPage = req.getParameterValues("__graphicPage"); ArrayList<String> graphicPageArray = new ArrayList<String>(); if (graphicPage != null) { // for (String s : graphicPage) { // p("graphicPage", s); // } graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage)); } // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size Rectangle pageSize = PageSize.LETTER; String pageSizeParameter = req.getParameter("rxPageSize"); if (pageSizeParameter != null) { if ("PageSize.HALFLETTER".equals(pageSizeParameter)) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(pageSizeParameter)) { pageSize = PageSize.A6; } else if ("PageSize.A4".equals(pageSizeParameter)) { pageSize = PageSize.A4; } } /* * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; } */ // p("size of page ", props.getProperty(PAGESIZE)); document.setPageSize(pageSize); // 285=left margin+width of box, 5f is space for looking nice document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom writer = PdfWriter.getInstance(document, baosPDF); writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal, patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint, imgFile, patientHIN, patientChartNo, pracNo, locale)); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); document.open(); document.newPage(); PdfContentByte cb = writer.getDirectContent(); BaseFont bf; // = normFont; cb.setRGBColorStroke(0, 0, 255); // render prescriptions for (String rxStr : listRx) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(5f); document.add(p); } // render additional notes if (additNotes != null && !additNotes.equals("")) { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(10f); document.add(p); } // render optometristEyeParam if (req.getAttribute("optometristEyeParam") != null) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph( new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(15f); document.add(p); } // render QrCode if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) { Integer scriptId = Integer.parseInt(req.getParameter("scriptId")); byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId); Image qrCode = Image.getInstance(qrCodeImage); document.add(qrCode); } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { logger.error("Error", e); } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } } logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); return baosPDF; }
From source file:pentaho.kettle.step.plugs.pdfout.PDFOutputGenerate.java
License:Apache License
public void generatePDF(String OutputFileName) throws IOException { if (Const.isWindows()) { if (OutputFileName.startsWith("file:///")) OutputFileName = OutputFileName.substring(8); OutputFileName = OutputFileName.replace("\\", "\\\\"); }/*from w w w .jav a 2s . c o m*/ Document document = new Document(); PdfWriter writer; try { writer = PdfWriter.getInstance(document, new FileOutputStream(OutputFileName)); document.open(); document.add(new Paragraph("Hello Rishu Here !!")); /* * Setting up File Attributes - Document Description */ document.addAuthor("Rishu Shrivastava"); document.addCreationDate(); document.addCreator("Rishu"); document.addTitle("Set Attribute Example"); document.addSubject("An example to show how attributes can be added to pdf files."); document.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:proyecto.Main.java
private void jp_flujo_guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jp_flujo_guardarMouseClicked JFileChooser jfc = new JFileChooser(); FileFilter filtro = new FileNameExtensionFilter("PNG", "png"); FileFilter filtro2 = new FileNameExtensionFilter("JPG", "jpg"); FileFilter filtro3 = new FileNameExtensionFilter("PDF", "pdf"); FileFilter filtro4 = new FileNameExtensionFilter("JPEG", "jpeg"); FileFilter filtro5 = new FileNameExtensionFilter("Dany", "dany"); jfc.addChoosableFileFilter(filtro);/* w w w .ja va2s . c o m*/ jfc.addChoosableFileFilter(filtro2); jfc.addChoosableFileFilter(filtro3); jfc.addChoosableFileFilter(filtro4); jfc.addChoosableFileFilter(filtro5); int op = jfc.showSaveDialog(jfc); if (op == JFileChooser.APPROVE_OPTION) { if (jfc.getFileFilter().getDescription().equals("PNG")) { try { BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_flujo.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".png"); ImageIO.write(bi, "png", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("JPG")) { try { BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_flujo.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".jpg"); ImageIO.write(bi, "jpg", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("PDF")) { try { Document documentPDF = new Document(); PdfWriter pdf = PdfWriter.getInstance(documentPDF, new FileOutputStream(jfc.getSelectedFile().getPath() + ".pdf")); documentPDF.open(); documentPDF.addAuthor("Dany Cheong"); documentPDF.addCreator("DC"); BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_flujo.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".png"); ImageIO.write(bi, "png", archivo); documentPDF.add(com.lowagie.text.Image.getInstance(jfc.getSelectedFile().toString() + ".png")); archivo.delete(); documentPDF.close(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("JPEG")) { try { BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_flujo.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".jpeg"); ImageIO.write(bi, "jpeg", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("Dany")) { if (jfc.getSelectedFile().exists()) {//si el archivo ya existe, y salvo el panel en ese mismo archivo try { File archivo = null; archivo = new File(jfc.getSelectedFile().getPath()); FileInputStream fis = new FileInputStream(archivo); ObjectInputStream ois = new ObjectInputStream(fis); Pane_temp panel; ArrayList<Pane_temp> lista2 = new ArrayList(); try { while ((panel = (Pane_temp) ois.readObject()) != null) { lista2.add(panel); } } catch (Exception e) { } finally { fis.close(); ois.close(); } for (int i = 0; i < lista.size(); i++) { lista2.add(lista.get(i)); } FileOutputStream fos = new FileOutputStream(archivo); ObjectOutputStream oos = new ObjectOutputStream(fos); for (Pane_temp temporal : lista2) { oos.writeObject(temporal); } oos.flush(); oos.close(); fos.close(); } catch (Exception e) { } } else { //si el archivo no existe y estoy creando uno nuevo File archivo = null; try { archivo = new File(jfc.getSelectedFile().getPath() + ".dany"); //crear archivo que no existe FileOutputStream fos = new FileOutputStream(archivo); ObjectOutputStream oos = new ObjectOutputStream(fos); for (int i = 0; i < lista.size(); i++) { oos.writeObject(lista.get(i)); } oos.flush(); fos.close(); oos.close(); lista.removeAll(lista); } catch (Exception ex) { ex.printStackTrace(); } finally { } } } } }
From source file:proyecto.Main.java
private void cr_red_guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cr_red_guardarMouseClicked JFileChooser jfc = new JFileChooser(); FileFilter filtro = new FileNameExtensionFilter("PNG", "png"); FileFilter filtro2 = new FileNameExtensionFilter("JPG", "jpg"); FileFilter filtro3 = new FileNameExtensionFilter("PDF", "pdf"); FileFilter filtro4 = new FileNameExtensionFilter("JPEG", "jpeg"); FileFilter filtro5 = new FileNameExtensionFilter("Dany", "dany"); jfc.addChoosableFileFilter(filtro);/*from w ww .j a va 2 s . com*/ jfc.addChoosableFileFilter(filtro2); jfc.addChoosableFileFilter(filtro3); jfc.addChoosableFileFilter(filtro4); jfc.addChoosableFileFilter(filtro5); int op = jfc.showSaveDialog(jfc); if (op == JFileChooser.APPROVE_OPTION) { if (jfc.getFileFilter().getDescription().equals("PNG")) { try { BufferedImage bi = new BufferedImage(jp_red.getWidth(), jp_red.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_red.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".png"); ImageIO.write(bi, "png", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("JPG")) { try { BufferedImage bi = new BufferedImage(jp_red.getWidth(), jp_red.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_red.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".jpg"); ImageIO.write(bi, "jpg", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("PDF")) { try { Document documentPDF = new Document(); PdfWriter pdf = PdfWriter.getInstance(documentPDF, new FileOutputStream(jfc.getSelectedFile().getPath() + ".pdf")); documentPDF.open(); documentPDF.addAuthor("Dany Cheong"); documentPDF.addCreator("DC"); BufferedImage bi = new BufferedImage(jp_red.getWidth(), jp_red.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_red.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".png"); ImageIO.write(bi, "png", archivo); documentPDF.add(com.lowagie.text.Image.getInstance(jfc.getSelectedFile().toString() + ".png")); archivo.delete(); documentPDF.close(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("JPEG")) { try { BufferedImage bi = new BufferedImage(jp_red.getWidth(), jp_red.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_red.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".jpeg"); ImageIO.write(bi, "jpeg", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("Dany")) { if (jfc.getSelectedFile().exists()) { try { File archivo = null; archivo = new File(jfc.getSelectedFile().getPath()); FileInputStream fis = new FileInputStream(archivo); ObjectInputStream ois = new ObjectInputStream(fis); Pane_temp panel; ArrayList<Pane_temp> lista2 = new ArrayList(); try { while ((panel = (Pane_temp) ois.readObject()) != null) { lista2.add(panel); } } catch (Exception e) { } finally { fis.close(); ois.close(); } for (int i = 0; i < lista.size(); i++) { lista2.add(lista.get(i)); } FileOutputStream fos = new FileOutputStream(archivo); ObjectOutputStream oos = new ObjectOutputStream(fos); for (Pane_temp temporal : lista2) { oos.writeObject(temporal); } oos.flush(); oos.close(); fos.close(); } catch (Exception e) { } } else { File archivo = null; try { archivo = new File(jfc.getSelectedFile().getPath() + ".dany"); //crear archivo que no existe FileOutputStream fos = new FileOutputStream(archivo); ObjectOutputStream oos = new ObjectOutputStream(fos); for (int i = 0; i < lista.size(); i++) { oos.writeObject(lista.get(i)); } oos.flush(); fos.close(); oos.close(); lista.removeAll(lista); } catch (Exception ex) { ex.printStackTrace(); } finally { } } } } }
From source file:proyecto.Main.java
private void cr_organigrama_guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cr_organigrama_guardarMouseClicked JFileChooser jfc = new JFileChooser(); FileFilter filtro = new FileNameExtensionFilter("PNG", "png"); FileFilter filtro2 = new FileNameExtensionFilter("JPG", "jpg"); FileFilter filtro3 = new FileNameExtensionFilter("PDF", "pdf"); FileFilter filtro4 = new FileNameExtensionFilter("JPEG", "jpeg"); FileFilter filtro5 = new FileNameExtensionFilter("Dany", "dany"); jfc.addChoosableFileFilter(filtro);/* w ww . j a va2s . c o m*/ jfc.addChoosableFileFilter(filtro2); jfc.addChoosableFileFilter(filtro3); jfc.addChoosableFileFilter(filtro4); jfc.addChoosableFileFilter(filtro5); int op = jfc.showSaveDialog(jfc); if (op == JFileChooser.APPROVE_OPTION) { if (jfc.getFileFilter().getDescription().equals("PNG")) { try { BufferedImage bi = new BufferedImage(jp_organigrama.getWidth(), jp_organigrama.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_organigrama.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".png"); ImageIO.write(bi, "png", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("JPG")) { try { BufferedImage bi = new BufferedImage(jp_organigrama.getWidth(), jp_organigrama.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_organigrama.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".jpg"); ImageIO.write(bi, "jpg", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("PDF")) { try { Document documentPDF = new Document(); PdfWriter pdf = PdfWriter.getInstance(documentPDF, new FileOutputStream(jfc.getSelectedFile().getPath() + ".pdf")); documentPDF.open(); documentPDF.addAuthor("Dany Cheong"); documentPDF.addCreator("DC"); BufferedImage bi = new BufferedImage(jp_organigrama.getWidth(), jp_organigrama.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_organigrama.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".png"); ImageIO.write(bi, "png", archivo); documentPDF.add(com.lowagie.text.Image.getInstance(jfc.getSelectedFile().toString() + ".png")); archivo.delete(); documentPDF.close(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("JPEG")) { try { BufferedImage bi = new BufferedImage(jp_organigrama.getWidth(), jp_organigrama.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); jp_organigrama.paint(g); File archivo = new File(jfc.getSelectedFile().toString() + ".jpeg"); ImageIO.write(bi, "jpeg", archivo); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else if (jfc.getFileFilter().getDescription().equals("Dany")) { if (jfc.getSelectedFile().exists()) { try { File archivo = null; archivo = new File(jfc.getSelectedFile().getPath()); FileInputStream fis = new FileInputStream(archivo); ObjectInputStream ois = new ObjectInputStream(fis); Pane_temp panel; ArrayList<Pane_temp> lista2 = new ArrayList(); try { while ((panel = (Pane_temp) ois.readObject()) != null) { lista2.add(panel); } } catch (Exception e) { } finally { fis.close(); ois.close(); } for (int i = 0; i < lista.size(); i++) { lista2.add(lista.get(i)); } FileOutputStream fos = new FileOutputStream(archivo); ObjectOutputStream oos = new ObjectOutputStream(fos); for (Pane_temp temporal : lista2) { oos.writeObject(temporal); } oos.flush(); oos.close(); fos.close(); } catch (Exception e) { } } else { File archivo = null; try { archivo = new File(jfc.getSelectedFile().getPath() + ".dany"); //crear archivo que no existe FileOutputStream fos = new FileOutputStream(archivo); ObjectOutputStream oos = new ObjectOutputStream(fos); for (int i = 0; i < lista.size(); i++) { oos.writeObject(lista.get(i)); } oos.flush(); fos.close(); oos.close(); lista.removeAll(lista); } catch (Exception ex) { ex.printStackTrace(); } finally { } } } } }
From source file:questions.metadata.UpdateModDate.java
public static void main(String[] args) { Document document = new Document(); try {/*from w w w . j av a 2s. c om*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(ORIGINAL)); document.addTitle("Hello World example"); document.addSubject("This example shows how to add metadata"); document.addKeywords("Metadata, iText, XMP"); document.addCreator("My program using iText"); document.addAuthor("Bruno Lowagie"); writer.createXmpMetadata(); document.open(); document.add(new Paragraph("Hello World")); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } PdfReader reader; try { reader = new PdfReader(ORIGINAL); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(MODIFIED)); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }