List of usage examples for com.itextpdf.text Document open
boolean open
To view the source code for com.itextpdf.text Document open.
Click Source Link
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfEven(String path) throws IOException, DocumentException { String DEFAULT_PATH = path; // TODO Instead of hard code path, pass in as argument File folder = new File(DEFAULT_PATH); FileNameFilter FileFilter = new FileNameFilter(); File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */ for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; }//from w w w .j av a 2 s .c om // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); // Split on a space '\s' String[] fileNames = fileNameWithoutExt.split("\\s"); if (fileNames.length != 2) { throw new RuntimeException("File name format is not in right format"); } String fileNameFirst = fileNames[0]; String fileNameSecond = fileNames[1]; System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond); String[] fileNameFirstParts = fileNameFirst.split("-"); String[] fileNameSecondParts = fileNameSecond.split("-"); // Project num is always the 1st part String projectNum = fileNameFirstParts[0]; if (!projectNum.equals(fileNameSecondParts[0])) { throw new RuntimeException("Filename needs to be renamed to the correct format"); } // Strip off the first and second lot number, parse into integers int firstLotNum; int secondLotNum; firstLotNum = Integer.parseInt(fileNameFirstParts[1]); secondLotNum = Integer.parseInt(fileNameSecondParts[1]); // Determine number of pages by difference of lot numbers // Read in the source document // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf PdfReader pdfFileReader = new PdfReader(file.getPath()); int mod = pdfFileReader.getNumberOfPages() % 2; if (pdfFileReader.equals(mod)) { throw new RuntimeException("File is not an even number of pages"); } Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); /* instantiates a new document to be made */ int numPages = secondLotNum - firstLotNum + 1; int p = 0; int j = 1; // Create a copy of the orignal source file. We will pick specific pages out below document.open(); while (j < numPages) { j++; if (j % 2 == 1) { j += 1; } firstLotNum++; String FileName = projectNum + "-" + (firstLotNum - 1) + ".pdf"; /* Dynamic file name */ document = new Document(PageSize.LETTER, 0, 0, 0, 0); PdfCopy copy = new PdfCopy(document, new FileOutputStream(DEFAULT_PATH + "//" + FileName)); if (j == 1) { newFileListing = ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n"); } else if (j > 1) { newFileListing += ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n"); } document.open(); p += 2; copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */ copy.addPage(copy.getImportedPage(pdfFileReader, p)); document.close(); } System.out.println("Number of Documents Created:" + numPages); System.out.println("Number of Documents Created:" + listOfFiles[i]); } }
From source file:com.unicauca.coordinacionpis.managedbean.RegistroFormatoAController.java
public void agregarMetadatos() { // create document and writer Document document = new Document(PageSize.A4); PdfWriter writer;/*from w w w . j a v a 2s. com*/ try { writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\aguaabril2016.pdf")); // add meta-data to pdf document.addAuthor("Memorynotfound"); document.addCreationDate(); document.addCreator("Memorynotfound.com"); document.addTitle("Add meta data to PDF"); document.addSubject("how to add meta data to pdf using itext"); document.addKeywords(metadatosAnteproyectos.getTitulo() + "," + metadatosAnteproyectos.getProfesor()); document.addLanguage(Locale.ENGLISH.getLanguage()); document.addHeader("type", "tutorial, example"); // add xmp meta data writer.createXmpMetadata(); document.open(); document.add(new Paragraph("Add meta-data to PDF using iText")); document.close(); } catch (FileNotFoundException ex) { Logger.getLogger(RegistroOfertaAcademicaController.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(RegistroOfertaAcademicaController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.VanLesh.macsv10.macs.Models.Pdf.java
License:GNU General Public License
public static void maker(Calculation calc) { try {/*from www . ja v a 2s . c o m*/ File pdfFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Report.pdf"); Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream(pdfFile)); doc.open(); addMetaData(doc, calc); addContent(doc, calc); doc.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.vectorprint.report.itext.TocOutputStream.java
License:Open Source License
@Override public void secondPass(InputStream firstPass, OutputStream orig) throws IOException { PdfReader reader = null;/*w w w .j a va2 s .c om*/ VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument(); try { reader = new PdfReader(firstPass); prepareToc(); // init fresh components for second pass styling StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance(); StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings()); _stylerFactory.setLayerManager(outer.getElementProducer()); _stylerFactory.setImageLoader(outer.getElementProducer()); outer.getStyleHelper().setStylerFactory(_stylerFactory); EventHelper event = outer.getEventHelper().getClass().newInstance(); event.setItextStylerFactory(_stylerFactory); event.setElementProvider(outer.getElementProducer()); ((DefaultElementProducer) outer.getElementProducer()).setPh(event); Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper()); PdfWriter w = PdfWriter.getInstance(d, orig); w.setPageEvent(event); outer.getStyleHelper().setVpd((VectorPrintDocument) d); _stylerFactory.setDocument(d, w); DocumentStyler ds = _stylerFactory.getDocumentStyler(); outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds)); d.open(); ds.styleAfterOpen(d, null); List outline = SimpleBookmark.getBookmark(reader); if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) { printToc(d, w, vpd); if (outline != null) { int cur = w.getCurrentPageNumber(); SimpleBookmark.shiftPageNumbers(outline, cur, null); } d.newPage(); } outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString()); for (int p = 1; p <= reader.getNumberOfPages(); p++) { Image page = Image.getInstance(w.getImportedPage(reader, p)); page.setAbsolutePosition(0, 0); d.setPageSize(page); d.newPage(); Chunk i = new Chunk(" "); if (vpd.getToc().containsKey(p)) { Section s = null; for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) { if (e.getKey() == p) { s = e.getValue().get(0); break; } } i.setLocalDestination(s.getTitle().getContent()); } d.add(i); w.getDirectContent().addImage(page); w.freeReader(reader); } if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) { printToc(d, w, vpd); } w.setOutlines(outline); if (outer.isWasDebug()) { event.setLastPage(outer.getWriter().getCurrentPageNumber()); d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210))); d.setMargins(5, 5, 5, 5); d.newPage(); outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString()); event.setDebugHereAfter(true); DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory); } d.close(); } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) { throw new VectorPrintRuntimeException(ex); } finally { if (reader != null) { reader.close(); } } }
From source file:com.verbox.PrintHtml.java
public static void RenderPDF_img_too(String inpHtml) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException, DocumentException, PrinterException { try {/*from w w w . j a v a 2 s .c o m*/ fullhtml = inpHtml; String replaceAll = fullhtml.replaceAll("../../image/", ""); Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf")); // step 3 document.open(); // step 4 XMLWorkerHelper worker = XMLWorkerHelper.getInstance(); InputStream is = new ByteArrayInputStream(replaceAll.getBytes(StandardCharsets.UTF_8)); worker.parseXHtml(writer, document, is, Charset.forName("UTF-8")); // step 5 document.close(); PreImgPrint(); } catch (DocumentException | IOException E) { JOptionPane.showMessageDialog(null, "Exeption on print or prepare image " + E); } }
From source file:com.vimbox.hr.LicensePDFGenerator.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w .j a v a 2 s .co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/pdf"); String fileName = request.getParameter("license_name"); String ext = fileName.substring(fileName.lastIndexOf(".") + 1); String path = System.getProperty("user.dir") + "/documents/licenses/" + fileName; path = path.replaceAll("%20", " "); if (ext.equalsIgnoreCase("pdf")) { FileInputStream baos = new FileInputStream(path); OutputStream os = response.getOutputStream(); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = baos.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); os.close(); } else { try { // Document Settings // Document document = new Document(); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); // Loading MC // PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); // the cell object PdfPCell cell; Image img = Image.getInstance(path); int indentation = 0; float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - indentation) / img.getWidth()) * 100; img.scalePercent(scaler); //img.scaleAbsolute(80f, 80f); cell = new PdfPCell(img); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); document.add(table); //-----------------------------------// document.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } } }
From source file:com.wabacus.system.assistant.PdfAssistant.java
License:Open Source License
public ByteArrayOutputStream showReportDataOnPdfWithTpl(ReportRequest rrequest, IComponentConfigBean ccbean) { boolean ispdfprint = rrequest.isPdfPrintAction(); PDFExportBean pdfbean = null;//from w w w . j a v a2 s. c o m if (ispdfprint) { pdfbean = ccbean.getPdfPrintBean(); } else if (ccbean.getDataExportsBean() != null) {//PDF?PDF<dataexport/> pdfbean = (PDFExportBean) ccbean.getDataExportsBean().getDataExportBean(Consts.DATAEXPORT_PDF); } if (pdfbean == null || pdfbean.getPdftemplate() == null || pdfbean.getPdftemplate().trim().equals("")) return null; if (pdfbean.getLstIncludeApplicationids() == null || pdfbean.getLstIncludeApplicationids().size() == 0) return null; Map<String, AbsReportType> mReportTypeObjs = new HashMap<String, AbsReportType>(); IComponentType cctypeObj; AbsReportType reportTypeObjTmp; int maxrowcount = 0; for (String appidTmp : pdfbean.getLstIncludeApplicationids()) {//?PDF if (mReportTypeObjs.containsKey(appidTmp)) continue; cctypeObj = rrequest.getComponentTypeObj(appidTmp, null, false); if (cctypeObj == null || !(cctypeObj instanceof AbsReportType)) continue; reportTypeObjTmp = (AbsReportType) cctypeObj; mReportTypeObjs.put(appidTmp, reportTypeObjTmp); if (reportTypeObjTmp.getLstReportData() != null && reportTypeObjTmp.getLstReportData().size() > maxrowcount) { maxrowcount = reportTypeObjTmp.getLstReportData().size(); } } if (mReportTypeObjs.size() == 0 || maxrowcount == 0) return null; try { Document document = new Document(); ByteArrayOutputStream baosResult = new ByteArrayOutputStream(); PdfCopy pdfCopy = new PdfCopy(document, baosResult); document.open(); for (int i = 0; i < maxrowcount; i++) { addPdfPageToDocument(pdfCopy, showReportOneRowDataOnPdf(rrequest, mReportTypeObjs, ccbean, pdfbean, i)); } document.close(); return baosResult; } catch (Exception e) { throw new WabacusRuntimeException("" + ccbean.getPath() + "?pdf", e); } }
From source file:com.wabacus.WabacusFacade.java
License:Open Source License
private static void exportReportDataOnPDF(String pageid, ReportRequest rrequest, WabacusResponse wresponse) { boolean success = true; try {//from www .j a v a 2 s .c om rrequest.setWResponse(wresponse); wresponse.setRRequest(rrequest); rrequest.init(pageid); if (rrequest.getLstAllReportBeans() == null || rrequest.getLstAllReportBeans().size() == 0) { throw new WabacusRuntimeException("?" + pageid + "?plainexcel???"); } Document document = new Document(); ByteArrayOutputStream baosResult = new ByteArrayOutputStream(); PdfCopy pdfCopy = new PdfCopy(document, baosResult); document.open(); boolean ispdfprint = rrequest.isPdfPrintAction(); for (IComponentConfigBean ccbeanTmp : rrequest.getLstComponentBeans()) {//??PDF? PDFExportBean pdfbeanTmp = null; if (ispdfprint) { pdfbeanTmp = ccbeanTmp.getPdfPrintBean(); } else if (ccbeanTmp.getDataExportsBean() != null) { pdfbeanTmp = (PDFExportBean) ccbeanTmp.getDataExportsBean() .getDataExportBean(Consts.DATAEXPORT_PDF); } if (pdfbeanTmp != null && pdfbeanTmp.getPdftemplate() != null && !pdfbeanTmp.getPdftemplate().trim().equals("")) { PdfAssistant.getInstance().addPdfPageToDocument(pdfCopy, PdfAssistant.getInstance().showReportDataOnPdfWithTpl(rrequest, ccbeanTmp)); } } AbsReportType reportTypeObjTmp; for (ReportBean rbTmp : rrequest.getLstAllReportBeans()) { reportTypeObjTmp = (AbsReportType) rrequest.getComponentTypeObj(rbTmp, null, false); if (rrequest.isReportInPdfTemplate(rbTmp.getId())) continue;//??PDF??? PdfAssistant.getInstance().addPdfPageToDocument(pdfCopy, reportTypeObjTmp.displayOnPdf()); } document.close(); BufferedOutputStream bos = null; if (rrequest.isExportToLocalFile()) { bos = new BufferedOutputStream(new FileOutputStream(new File(rrequest.getDataExportFilepath()))); } else { if (!ispdfprint) { String title = WabacusAssistant.getInstance().encodeAttachFilename(rrequest.getRequest(), rrequest.getDataExportFilename()); wresponse.getResponse().setHeader("Content-disposition", "attachment;filename=" + title + ".pdf"); } wresponse.getResponse().setContentLength(baosResult.size()); bos = new BufferedOutputStream(wresponse.getResponse().getOutputStream()); } baosResult.writeTo(bos); bos.close(); baosResult.close(); if (rrequest.isExportToLocalFile() && rrequest.isDataexport_localstroagezip()) { tarDataFile(rrequest); } } catch (WabacusRuntimeTerminateException wrwe) { if (wresponse.getStatecode() == Consts.STATECODE_FAILED) { success = false; } } catch (Exception wre) { wresponse.setStatecode(Consts.STATECODE_FAILED); log.error("?" + rrequest.getPagebean().getId() + "", wre); success = false; } finally { rrequest.destroy(success); } doPostDataExport(rrequest, wresponse); }
From source file:com.warehouse.abstractController.OrderMenuAbstractController.java
public void handleGeneratePDF() { try {/*from ww w.j av a2 s . c om*/ OutputStream file = new FileOutputStream(new File("./Test.pdf")); Document document = new Document(); PdfWriter.getInstance(document, file); document.open(); document.add(new Paragraph("Order information")); for (Order o : orderDao.getOrderList()) if (o.getId() == Integer.parseInt(Cookie.getInstance().get("orderID"))) document.add(new Paragraph("Order (" + o.getId() + ") " + o.getItems() + " " + o.getDate() + " " + o.getClient().getPhone())); document.add(new Paragraph(new Date().toString())); document.close(); file.close(); AlertBox.getInstance().display(getClass().getSimpleName(), "Successful generated *.PDF file !"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.wesley.creche.services.pdf.createHrPdf.java
public void writePdfHrReport() throws DocumentException, IOException, SQLException { createFolderIfNotExist();//from w ww.j a v a 2s . com Date date = new Date(); DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); String today = df.format(date); String fileName = "C:\\creche\\reports\\HRReport" + today + "_.pdf"; Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); addTitle(document); addLine(document); addEmptyLine(document, 2); try { document.add(new Paragraph(getEmpName())); } catch (ClassNotFoundException ex) { Logger.getLogger(createHrPdf.class.getName()).log(Level.SEVERE, null, ex); } try { document.add(new Paragraph(getEmpLastName())); } catch (ClassNotFoundException ex) { Logger.getLogger(createHrPdf.class.getName()).log(Level.SEVERE, null, ex); } document.close(); }