List of usage examples for com.itextpdf.text Document newPage
public boolean newPage()
From source file:Controller.app.ConsultaController.java
private File createPDF(TblServicioFactura factura) throws IOException { String data = factura.getTesPagoResponse(); JSONObject obj = new JSONObject(data); JSONArray content = obj.getJSONArray("lineaFactura"); String temp = ""; File _file = null;/*from w w w .ja v a2s . co m*/ Document doc = null; OutputStream file = null; int page = 0; try { _file = File.createTempFile("temp_file", ".pdf"); TblServicioServicio servicio = servicios.search(factura.getTesCodigoSintesisBi().toString()); file = new FileOutputStream(_file); doc = new Document(PageSize.LETTER); doc.setMargins(servicio.getMarginLeft().floatValue(), servicio.getMarginRight().floatValue(), servicio.getMarginTop().floatValue(), servicio.getMarginBottom().floatValue()); PdfWriter.getInstance(doc, file); doc.open(); // ClassLoader classloader = Thread.currentThread().getContextClassLoader(); ClassLoader classloader = getClass().getClassLoader(); URL url = classloader.getResource("cour.ttf"); BaseFont base = null; if (url == null) { base = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } else { String path = url.getPath(); if ("/".equals(path.substring(0, 1))) { path = path.substring(1); } Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, path); base = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } Font f = new Font(base, servicio.getFontSize(), Font.NORMAL, BaseColor.BLACK); String qr = ""; float line = 0; for (Object item : content) { Paragraph paragraph = new Paragraph(item.toString(), f); if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) { if (item.toString().contains("P X#X&$#&K##")) { paragraph = new Paragraph(" ", f); doc.add(paragraph); doc.add(paragraph); paragraph = new Paragraph(item.toString(), f); } } if (item.toString().contains("<b>")) { Font bold = new Font(base, 7.0f, Font.BOLD, BaseColor.BLACK); paragraph = new Paragraph(item.toString().replace("<b>", ""), bold); } if (item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>")) { qr = item.toString().replaceAll("<QR>", ""); qr = item.toString().replaceAll("<QR_ENT_G>", ""); Image image = QR.create(qr); image.scaleAbsolute(servicio.getQrScale().floatValue(), servicio.getQrScale().floatValue()); if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL") || servicio.getTesDetalleVc().trim().equals("PAGO TELECEL") || servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL") || servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) { float y = (doc.getPageSize().getHeight() - (paragraph.getLeading() * (line + 1))); float x = 0; if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) { image.setAlignment(Image.ALIGN_RIGHT); x = doc.getPageSize().getWidth() - (110 - servicio.getMarginLeft().floatValue()); } if (servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")) { image.setAlignment(Image.ALIGN_LEFT); x = 30; y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading() * 2)); } if (servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")) { image.setAlignment(Image.ALIGN_LEFT); x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue()); y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading())); } if (servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) { image.setAlignment(Image.ALIGN_LEFT); x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue()); y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading())); } image.setAbsolutePosition(x, y); } doc.add(image); } if (servicio.getDelimitador().equals(item.toString().trim())) { line = 0; page++; doc.newPage(); } else { line += 1f; if (!(item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>"))) { doc.add(paragraph); } } temp += item.toString(); } } catch (FileNotFoundException ex) { Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex); } catch (DocumentException | IOException ex) { Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex); } doc.close(); file.close(); return _file; }
From source file:controllers.PdfViewer.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*from www . j a v a 2s. co m*/ * @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"); try { AWSUtils utils = new AWSUtils(); // InputStream reader = (InputStream)utils.readBucket("hilearnfiles", "Bursary.pdf"); //file BufferedReader is = utils.readBucket("hilearnfiles", "Bursary.pdf"); // String text = IOUtils.toString(is, StandardCharsets.UTF_8); OutputStream out = new FileOutputStream("text.pdf"); byte[] buffer = new byte[1024]; String line = "No Content"; while (is.readLine() != null) { line = is.readLine(); // System.out.println("Line " + buffer); // out.write(); } // step 1 Document document = new Document(); // step 2 // PdfWriter.getInstance(document, new FileOutputStream("c:/sample.pdf")); PdfWriter.getInstance(document, response.getOutputStream()); // step 3 document.open(); // step 4 document.add(new Paragraph(line)); document.newPage(); // document.add(new Paragraph(new Date().toString())); // step 5 document.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } }
From source file:cz.zcu.kiv.eegdatabase.logic.pdf.ReservationPDF.java
License:Apache License
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { try {// w ww. java2 s. co m if (request.getParameter("type").compareTo("single") == 0) { int id = Integer.parseInt(request.getParameter("reservationId")); Reservation reservation = reservationDao.getReservationById(id); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=reservation-" + id + ".pdf"); Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); document.open(); PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/")); document.add(utils.setHeader(document, "Reservation listing")); /*Paragraph paragraph = new Paragraph("Reservation #" + id, FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, BaseColor.BLACK)); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.setSpacingBefore(10); paragraph.setSpacingAfter(10); document.add(paragraph);*/ document.add(formatReservation(reservation)); document.close(); response.flushBuffer(); return null; } if (request.getParameter("type").compareTo("range") == 0) { String date = request.getParameter("date") + " 00:00:00"; GregorianCalendar rangeStart = BookingRoomUtils.getCalendar(date); int length = Integer.parseInt(request.getParameter("length")); GregorianCalendar rangeEnd = (GregorianCalendar) rangeStart.clone(); rangeEnd.add(Calendar.DAY_OF_YEAR, length); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=reservations.pdf"); Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); document.open(); PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/")); document.add(utils.setHeader(document, "Reservations listing")); java.util.List<Reservation> reservations = reservationDao.getReservationsBetween(rangeStart, rangeEnd, "", 0); int count = 0; for (Reservation reservation : reservations) { document.add(formatReservation(reservation)); if (++count % 6 == 0) { document.newPage(); document.add(utils.setHeader(document, "Reservations listing")); } } document.close(); response.flushBuffer(); return null; } return null; } catch (Exception e) { ModelAndView mav = new ModelAndView(getFormView()); Map data = new HashMap<String, Object>(); data.put("error", e.getMessage()); mav.addAllObjects(data); return mav; } }
From source file:de.aidger.utils.pdf.BalanceReportConverter.java
License:Open Source License
/** * Places the created document onto the template for this report. * // w ww . j a va2 s .c o m * @param file * The file to which this report will be saved. * @param preTemplateFile * The report to be used. */ private boolean applyTemplate(File file, File preTemplateFile) { FileOutputStream outStream = null; FileInputStream inStream = null; PdfContentByte contentByte = null; PdfReader reader = null, templateReader = null; try { /* * Use the template located in the configuration path first, if it * exists. */ File template = new File( Runtime.getInstance().getConfigPath() + "/templates/BalanceReportTemplate.pdf"); URL templateURL = null; if (template.exists()) { templateURL = template.toURI().toURL(); } else { templateURL = getClass().getResource("/de/aidger/res/pdf/BalanceReportTemplate.pdf"); } if (templateURL == null) { throw new FileNotFoundException(_("The report template could not be loaded.") + " " + _("Please make sure that a fitting template exists in the template folder.")); } Document document = new Document(PageSize.A4.rotate()); outStream = new FileOutputStream(file.getPath()); inStream = new FileInputStream(preTemplateFile); writer = PdfWriter.getInstance(document, outStream); document.open(); contentByte = writer.getDirectContent(); reader = new PdfReader(inStream); templateReader = new PdfReader(templateURL); /* * Add the template pdf to the document and place the finished * report on top of it. */ for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = writer.getImportedPage(templateReader, 1); int rotation = templateReader.getPageRotation(1); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } document.close(); return true; } catch (FileNotFoundException e) { if (e.getMessage() != null) { UI.displayError(e.getMessage()); } } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
From source file:de.aidger.utils.pdf.BudgetReportConverter.java
License:Open Source License
/** * Places the created document onto the template for this report. * //from w ww. java 2 s .c o m * @param file * The file to which this report will be saved. * @param preTemplateFile * The report to be used. */ private boolean applyTemplate(File file, File preTemplateFile) { FileOutputStream outStream = null; FileInputStream inStream = null; PdfContentByte contentByte = null; PdfReader reader = null, templateReader = null; try { /* * Use the template located in the configuration path first, if it * exists. */ File template = new File(Runtime.getInstance().getConfigPath() + "/templates/BudgetReportTemplate.pdf"); URL templateURL = null; if (template.exists()) { templateURL = template.toURI().toURL(); } else { templateURL = getClass().getResource("/de/aidger/res/pdf/BudgetReportTemplate.pdf"); } if (templateURL == null) { throw new FileNotFoundException(_("The report template could not be loaded.") + " " + _("Please make sure that a fitting template exists in the template folder.")); } Document document = new Document(PageSize.A4); outStream = new FileOutputStream(file.getPath()); inStream = new FileInputStream(preTemplateFile); writer = PdfWriter.getInstance(document, outStream); document.open(); contentByte = writer.getDirectContent(); reader = new PdfReader(inStream); templateReader = new PdfReader(templateURL); /* * Add the template pdf to the document and place the finished * report on top of it. */ for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = writer.getImportedPage(templateReader, 1); int rotation = templateReader.getPageRotation(1); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } document.close(); return true; } catch (FileNotFoundException e) { if (e.getMessage() != null) { UI.displayError(e.getMessage()); } } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
From source file:de.aidger.utils.pdf.ControllingConverter.java
License:Open Source License
/** * Places the created document onto the template for this report. * /*w w w . ja v a 2 s . com*/ * @param file * The file to which this report will be saved. * @param preTemplateFile * The report to be used. */ private boolean applyTemplate(File file, File preTemplateFile) { FileOutputStream outStream = null; FileInputStream inStream = null; PdfContentByte contentByte = null; PdfReader reader = null, templateReader = null; try { /* * Use the template located in the configuration path first, if it * exists. */ File template = new File(Runtime.getInstance().getConfigPath() + "/templates/ControllingTemplate.pdf"); URL templateURL = null; if (template.exists()) { templateURL = template.toURI().toURL(); } else { templateURL = getClass().getResource("/de/aidger/res/pdf/ControllingTemplate.pdf"); } if (templateURL == null) { throw new FileNotFoundException(_("The report template could not be loaded.") + " " + _("Please make sure that a fitting template exists in the template folder.")); } Document document = new Document(PageSize.A4); outStream = new FileOutputStream(file.getPath()); inStream = new FileInputStream(preTemplateFile); writer = PdfWriter.getInstance(document, outStream); document.open(); contentByte = writer.getDirectContent(); reader = new PdfReader(inStream); templateReader = new PdfReader(templateURL); /* * Add the template pdf to the document and place the finished * report on top of it. */ for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = writer.getImportedPage(templateReader, 1); int rotation = templateReader.getPageRotation(1); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } document.close(); return true; } catch (FileNotFoundException e) { if (e.getMessage() != null) { UI.displayError(e.getMessage()); } } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
From source file:de.aidger.utils.pdf.ProtocolConverter.java
License:Open Source License
/** * Places the created document onto the template for this report. * //from w ww. j av a 2 s.co m * @param file * The file to which this report will be saved. * @param preTemplateFile * The report to be used. */ private boolean applyTemplate(File file, File preTemplateFile) { FileOutputStream outStream = null; FileInputStream inStream = null; PdfContentByte contentByte = null; PdfReader reader = null, templateReader = null; try { /* * Use the template located in the configuration path first, if it * exists. */ File template = new File(Runtime.getInstance().getConfigPath() + "/templates/ProtocolTemplate.pdf"); URL templateURL = null; if (template.exists()) { templateURL = template.toURI().toURL(); } else { templateURL = getClass().getResource("/de/aidger/res/pdf/ProtocolTemplate.pdf"); } if (templateURL == null) { throw new FileNotFoundException(_("The report template could not be loaded.") + " " + _("Please make sure that a fitting template exists in the template folder.")); } Document document = new Document(PageSize.A4.rotate()); outStream = new FileOutputStream(file.getPath()); inStream = new FileInputStream(preTemplateFile); writer = PdfWriter.getInstance(document, outStream); document.open(); contentByte = writer.getDirectContent(); reader = new PdfReader(inStream); templateReader = new PdfReader(templateURL); /* * Add the template pdf to the document and place the finished * report on top of it. */ for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = writer.getImportedPage(templateReader, 1); int rotation = templateReader.getPageRotation(1); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { //landscape mode contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight()); } else { //portrait mode contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } document.close(); return true; } catch (FileNotFoundException e) { if (e.getMessage() != null) { UI.displayError(e.getMessage()); } } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
From source file:de.alpharogroup.swing.img.ImageExtensions.java
License:Open Source License
/** * Creates from the given Collection of images an pdf file. * * @param result//w ww . ja v a2s . c o m * the output stream from the pdf file where the images shell be written. * @param images * the BufferedImage collection to be written in the pdf file. * @throws DocumentException * is thrown if an error occurs when trying to get an instance of {@link PdfWriter}. * @throws IOException * Signals that an I/O exception has occurred. */ public static void createPdf(final OutputStream result, final List<BufferedImage> images) throws DocumentException, IOException { final Document document = new Document(); PdfWriter.getInstance(document, result); for (final BufferedImage image : images) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); final Image img = Image.getInstance(baos.toByteArray()); document.setPageSize(img); document.newPage(); img.setAbsolutePosition(0, 0); document.add(img); } document.close(); }
From source file:de.beimax.talenttree.PDFGenerator.java
License:Open Source License
public void generate() throws Exception { // create PDF Document document = new Document(pageSizeValue, marginHorizontal, marginHorizontal, marginVertical, marginVertical);/*from ww w .j av a2 s . c o m*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(getFileName())); document.open(); document.addAuthor("Maximilian Kalus"); document.addCreator( "Star Wars Talent Tree Generator, see https://github.com/mkalus/sw-talenttree-generator"); document.addTitle(strings.getProperty("PDFTitle", "Star Wars Talent Trees")); // iterate data files to generate PDF for (Object o : this.data) { Map data = (Map) o; // to map // check type String type = (String) data.get("type"); if (type == null) throw new Exception("The following data contained no type: " + o.toString()); // try to load class and create instance AbstractPageGenerator abstractPageGenerator; try { Class c = Class.forName(type); abstractPageGenerator = (AbstractPageGenerator) c.newInstance(); if (abstractPageGenerator == null) throw new Exception(); } catch (Exception e) { throw new Exception("Type " + type + " not valid in following data: " + o.toString()); } // new page, if needed document.newPage(); PdfContentByte canvas = writer.getDirectContent(); // fill data abstractPageGenerator.setGenerator(this); abstractPageGenerator.setDocument(document); abstractPageGenerator.setWriter(writer); abstractPageGenerator.setCanvas(canvas); abstractPageGenerator.setData(data); // generate page abstractPageGenerator.generate(); } // close and write document document.close(); }
From source file:de.mat.utils.pdftools.PdfResize.java
License:Mozilla Public License
/** /**//from w w w . j a v a 2 s. co m * <h4>FeatureDomain:</h4> * PublishingTools * <h4>FeatureDescription:</h4> * scales and move comntents of the pdf pages from fileSrc and output to * fileNew * <h4>FeatureResult:</h4> * <ul> * <li>create PDF - fileNew * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param fileSrc - source-pdf * @param fileNew - scaled dest-pdf * @param factorX - scaling x * @param factorY - scaling y * @param pixelLeft - move right * @param pixelTop - move down * @throws Exception */ public static void resizePdf(String fileSrc, String fileNew, float factorX, float factorY, float pixelLeft, float pixelTop) throws Exception { // open reader PdfReader reader = new PdfReader(fileSrc); // get pagebasedata int pageCount = reader.getNumberOfPages(); Rectangle psize = reader.getPageSize(1); float width = psize.getHeight(); float height = psize.getWidth(); // open writer Document documentNew = new Document(new Rectangle(height * factorY, width * factorX)); PdfWriter writerNew = PdfWriter.getInstance(documentNew, new FileOutputStream(fileNew)); documentNew.open(); PdfContentByte cb = writerNew.getDirectContent(); // iterate pages int i = 0; while (i < pageCount) { i++; // imoport page from reader and scale it to writer documentNew.newPage(); PdfImportedPage page = writerNew.getImportedPage(reader, i); cb.addTemplate(page, factorX, 0, 0, factorY, pixelLeft, pixelTop); if (LOGGER.isInfoEnabled()) LOGGER.info("AddPage " + i + " from:" + fileSrc + " to:" + fileNew); } documentNew.close(); writerNew.close(); }