List of usage examples for com.lowagie.text Document open
boolean open
To view the source code for com.lowagie.text Document open.
Click Source Link
From source file:it.govpay.web.console.pagamenti.gde.exporter.PdfExporter.java
License:Open Source License
public static void exportAsPdf(List<EventoBean> eventi, ByteArrayOutputStream baos, IEventiService eventiService) throws DocumentException, UtilsException { Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); addMetaData(document);//from w w w .j av a 2s. c om addTitlePage(document); // Start a new page document.newPage(); addContent(document, eventi, eventiService); document.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/* ww w. j a va 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// w w w .j av a 2 s . com */ 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 v a 2 s . c om*/ */ 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/*from ww w.ja v a 2s .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 www. j a v a 2 s. c o m*/ * @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"); }
From source file:it.prato.comune.tolomeo.web.TolomeoPrintPDFServlet.java
License:Open Source License
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LogInterface logger = getLogger(request); String titolo = request.getParameter("titolo"); String descrizione = request.getParameter("descrizione"); String scala = request.getParameter("scala"); String mapx = request.getParameter("mapx"); String mapy = request.getParameter("mapy"); //creo URL alla mappa URL urlMappa = new URL(URLDecoder.decode(request.getParameter("urlMappa"), "UTF-8")); URI uriMappa = null;/* w ww. j av a2s .c o m*/ try { uriMappa = new URI(urlMappa.getProtocol(), null, urlMappa.getHost(), urlMappa.getPort(), urlMappa.getPath(), urlMappa.getQuery() + "&mode=map&scale=" + scala + "&mapxy=" + mapx + "+" + mapy + "&map_size=500 500", null); logger.info("URI di stampa mappa: " + uriMappa); } catch (URISyntaxException e) { logger.error("URI errore di sintassi", e); } Font BOLD15 = new Font(Font.HELVETICA, 15, Font.BOLD); Font FONT12 = new Font(Font.HELVETICA, 12, Font.NORMAL); Font FONT10 = new Font(Font.HELVETICA, 10, Font.NORMAL); Document doc = new Document(); ; PdfWriter pdf = null; Paragraph par = new Paragraph(); try { //creo il PDF response.setContentType("application/pdf"); pdf = PdfWriter.getInstance(doc, response.getOutputStream()); //attributi file doc.addTitle("Mappa di Prato"); doc.addAuthor("Comune di Prato"); doc.open(); //intestazione par.setAlignment(Paragraph.ALIGN_CENTER); print("Comune di Prato", BOLD15, par, doc); print(titolo, FONT10, par, doc); print("", FONT10, par, doc); //mappa Image mappa = Image.getInstance(uriMappa.toURL()); mappa.setAlignment(Image.MIDDLE); mappa.setBorder(Rectangle.BOX); mappa.setBorderWidth(1f); doc.add(mappa); } catch (Exception e) { logger.error("Errore durante la creazione del PDF", e); printErr(doc); } finally { doc.close(); pdf.close(); response.getOutputStream().close(); } }
From source file:javaaxp.xps2pdf.service.impl.PDFConverterImpl.java
License:Open Source License
@Override public void covertToPDF(OutputStream ouput) throws XPSError { try {//from w ww .j a v a 2 s . c om int firstPage = fPageController.getXPSAccess().getPageAccess(0).getFirstPageNum(); int lastPage = fPageController.getXPSAccess().getPageAccess(0).getLastPageNum(); Document document = new Document(); document.setPageCount(lastPage - firstPage + 1); document.setPageSize(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, ouput); document.open(); PdfContentByte cb = writer.getDirectContent(); for (int i = firstPage; i < 1; i++) { System.out.println("Converting page " + i); fPageController.setPage(i); PdfTemplate tp = cb.createTemplate((float) fPageController.getPage().getWidth(), (float) fPageController.getPage().getHeight()); Graphics g = tp.createGraphics((float) fPageController.getPage().getWidth(), (float) fPageController.getPage().getHeight()); JComponent toReturn = fPageViewer.getPageRenderer().getRendererComponent(); toReturn.paint(g); cb.addTemplate(tp, 0, 0); document.newPage(); } document.close(); } catch (DocumentException e) { //rethrow } }
From source file:jdbreport.model.io.pdf.itext2.PdfWriter.java
License:Apache License
public void save(OutputStream out, ReportBook reportBook) throws SaveReportException { double oldScaleX = GraphicUtil.getScaleX(); double oldScaleY = GraphicUtil.getScaleY(); try {//from w w w .j ava2 s . c om GraphicUtil.setScaleX(1); GraphicUtil.setScaleY(1); ReportPage pageFormat; int i = 0; while (i < reportBook.size() - 1 && !reportBook.getReportModel(i).isVisible()) { i++; } pageFormat = reportBook.getReportModel(i).getReportPage(); Paper paper = pageFormat.getPaper(); Rectangle pageSize = new Rectangle(Math.round((float) paper.getWidth()), Math.round((float) paper.getHeight())); if (pageFormat.getOrientation() == ReportPage.LANDSCAPE) { pageSize = pageSize.rotate(); } Document document = new Document(pageSize, Math.round((float) pageFormat.getLeftMargin(Units.PT)), Math.round((float) pageFormat.getRightMargin(Units.PT)), Math.round((float) pageFormat.getTopMargin(Units.PT)), Math.round((float) pageFormat.getBottomMargin(Units.PT))); try { com.lowagie.text.pdf.PdfWriter.getInstance(document, out); document.addTitle(reportBook.getReportCaption()); document.addCreator("JDBReport using iText"); document.addAuthor(System.getProperty("user.name")); document.open(); int listCount = 0; try { for (ReportModel model : reportBook) { if (model.isVisible()) { listCount = saveSheet(document, listCount, model); } } document.close(); } catch (IOException e) { e.printStackTrace(); } } catch (DocumentException e) { throw new SaveReportException(e); } } finally { GraphicUtil.setScaleX(oldScaleX); GraphicUtil.setScaleY(oldScaleY); } }
From source file:jdraw.JDrawApplication.java
private void saveAsPDF() { JDocumentFrame frame = (JDocumentFrame) jDesktopPane1.getSelectedFrame(); if (frame == null) { return;/*from w ww. ja v a 2 s . c o m*/ } JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter( java.util.ResourceBundle.getBundle("main").getString("filter_pdf"), "pdf")); chooser.setDialogTitle(java.util.ResourceBundle.getBundle("main").getString("dialog_export_as_pdf")); File f = chooser.getCurrentDirectory(); f = new File(f.getPath(), frame.getDocument().getName() + ".pdf"); chooser.setSelectedFile(f); if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } JDocument doc = frame.getDocument(); f = chooser.getSelectedFile(); if (f.exists() && JOptionPane.showConfirmDialog(this, f.getName() + java.util.ResourceBundle .getBundle("main").getString("msg_is_exist_overwrite")) != JOptionPane.OK_OPTION) { return; } frame.getViewer().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); com.lowagie.text.Document pDoc = new com.lowagie.text.Document(); try { FileOutputStream wt = new FileOutputStream(f); BufferedOutputStream bout = new BufferedOutputStream(wt); com.lowagie.text.pdf.PdfWriter pwriter = com.lowagie.text.pdf.PdfWriter.getInstance(pDoc, bout); pDoc.open(); FontFactory.registerDirectories(); Set set = FontFactory.getRegisteredFonts(); for (int i = 0; i < doc.size(); i++) { JPage cPage = doc.get(i); PageFormat pFormat = cPage.getPageFormat(); com.lowagie.text.Rectangle rc = new com.lowagie.text.Rectangle((float) pFormat.getWidth(), (float) pFormat.getHeight()); float left = (float) (pFormat.getImageableX()); float right = (float) (pFormat.getWidth() - pFormat.getImageableWidth() - left); float top = (float) pFormat.getImageableX(); float bottom = (float) (pFormat.getHeight() - pFormat.getImageableHeight() - top); pDoc.newPage(); com.lowagie.text.pdf.PdfContentByte cb = pdfContentByte = pwriter.getDirectContent(); cb.saveState(); Graphics2D g2 = (com.lowagie.text.pdf.PdfGraphics2D) cb.createGraphics((float) pFormat.getWidth(), (float) pFormat.getHeight()); boolean vg = cPage.getGuidLayer().isVisible(); cPage.getGuidLayer().setVisible(false); cPage.paint(new Rectangle.Double(0, 0, pFormat.getWidth(), pFormat.getHeight()), g2); cPage.getGuidLayer().setVisible(vg); g2.dispose(); cb.restoreState(); } pDoc.close(); } catch (Exception e) { JOptionPane.showConfirmDialog(this, e.getMessage(), "", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE); } frame.getViewer().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }