List of usage examples for com.itextpdf.text Image setAbsolutePosition
public void setAbsolutePosition(final float absoluteX, final float absoluteY)
Image
. From source file:NPRImpl.java
@Override public boolean saveRegistrationToPdf(RegistrationImpl registrationImpl, ResidentImpl residentImpl) throws RemoteException { try {/*from www .j av a 2 s . c o m*/ BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt")); String path = ""; try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } path = sb.toString().trim(); } finally { br.close(); } String gend = ""; Document doc = new Document(); FileOutputStream fos = new FileOutputStream(path + "\\registration\\" + residentImpl.getLName().trim() + ", " + residentImpl.getFName().trim() + "RegistrationResidentForm.pdf"); PdfWriter pdfWriter = PdfWriter.getInstance(doc, fos); PdfReader pdfReader = new PdfReader("RegistrationResidentForm.pdf"); PdfStamper pdfStamper = new PdfStamper(pdfReader, fos); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getOverContent(i); if (residentImpl.getPicture() != null) { Image image1 = Image.getInstance(residentImpl.getPicture()); image1.scaleAbsolute(95, 105); image1.setAbsolutePosition(465f, 635f); content.addImage(image1); } //Text over the existing page BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED); content.beginText(); content.setFontAndSize(bf, 10); //last name content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getLName().trim(), 175, 610, 0); //first name content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getFName().trim(), 325, 610, 0); //middle name content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getMName().trim(), 470, 610, 0); //college content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getCollege().trim(), 180, 582, 0); //Course and year content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getCourse().trim() + " - " + registrationImpl.getYear().trim(), 180, 568, 0); //department content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getDepartment().trim(), 400, 582, 0); //Sex content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getGender().trim(), 400, 568, 0); //Home address content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getAddress().trim(), 110, 540, 0); //resident mobile no1 content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMobile_number().trim(), 187, 485, 0); //resident mobile no2 content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMobile_number2().trim(), 187, 470, 0); //student email content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getEmail().trim(), 397, 485, 0); //fathers name content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherName().trim(), 110, 443, 0); //fathers area code content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherAreaCode().trim(), 300, 443, 0); //father landline content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherPhone().trim(), 355, 443, 0); //father mobile content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherMobile().trim(), 490, 443, 0); //father email content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherEmail().trim(), 110, 430, 0); //mother name content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherName().trim(), 110, 402, 0); //mother area code content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherAreaCode().trim(), 300, 402, 0); //mother landline content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherPhone().trim(), 355, 402, 0); //mother mobile content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherMobile().trim(), 490, 402, 0); //mother email content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherEmail().trim(), 110, 387, 0); //guardian name content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianName().trim(), 170, 335, 0); //guardian contact number content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianMobile().trim(), 470, 335, 0); //guardian address content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianAddress().trim(), 125, 322, 0); //guardian relation content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianRelation().trim(), 170, 307, 0); content.setFontAndSize(bf, 12); //room details content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Room No.: " + registrationImpl.getRoom_number().trim() + " - " + registrationImpl.getRoom_type().trim(), 355, 235, 0); content.endText(); } pdfStamper.close(); pdfReader.close(); fos.close(); pdfWriter.close(); } catch (DocumentException | FileNotFoundException ex) { // Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex); label.setText(ex.getMessage()); return false; } catch (IOException ex) { // Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex); label.setText(ex.getMessage()); return false; } return true; }
From source file:PrefichaPDF.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w w w.j av a2 s . c om*/ response.setContentType("application/pdf"); String curp = new String(request.getParameter("curp").getBytes("ISO-8859-1"), "UTF-8"); ConexionOracle conexionOracle = new ConexionOracle(); String sql = "select * from PERSONALDATA_ASP_TAB where curp=" + "'" + curp + "'"; System.out.println(sql); System.out.println("Esta es la curp: " + curp); conexionOracle.conectar(); Connection conn = conexionOracle.getConnection(); // driver@machineName:port:SID , userid, password Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); while (rset.next()) { fichabd = rset.getString("id_aspirante"); periodobd = rset.getString("periodo_solicitud"); prefichabd = rset.getString("preficha"); nombrebd = rset.getString("nombre"); String appat = rset.getString("apellido_pat"); String apmat = rset.getString("apellido_mat"); apellidosbd = appat + " " + apmat; curpbd = rset.getString("curp"); carrerabd = rset.getString("carrera"); modalidadbd = rset.getString("modalidad"); } try { Document preficha = new Document(); PdfWriter writer = PdfWriter.getInstance(preficha, response.getOutputStream()); preficha.open(); //encabezado //encabezado //encabezado //encabezado // documento.add(vacio); // documento.add(vacio); // documento.add(vacio); Paragraph depto = new Paragraph("Departamento de servicios escolares", FontFactory.getFont("arial", 20, Font.BOLD)); depto.setAlignment(Element.ALIGN_CENTER); preficha.add(depto); Paragraph vacio = new Paragraph(" ", FontFactory.getFont("arial", 10, Font.BOLD)); vacio.setAlignment(Element.ALIGN_CENTER); preficha.add(vacio); preficha.add(vacio); // preficha.add(vacio); //cuerpo //cuerpo //cuerpo //cuerpo //cuerpo Paragraph periodo_text = new Paragraph("Convocatoria de nuevo ingreso periodo: " + periodobd, FontFactory.getFont("arial", 10, Font.BOLD)); periodo_text.setAlignment(Element.ALIGN_CENTER); preficha.add(periodo_text); preficha.add(vacio); preficha.add(vacio); Paragraph fotografia = new Paragraph("Fotografa", FontFactory.getFont("arial", 10, Font.BOLD)); fotografia.setAlignment(Element.ALIGN_CENTER); preficha.add(fotografia); PdfContentByte rectangulo_general = writer.getDirectContentUnder(); rectangulo_general.rectangle(50, 48, 500, 710); rectangulo_general.fill(); drawRectangleSC(rectangulo_general, 50, 48, 500, 710); PdfContentByte rectangulo_periodo = writer.getDirectContentUnder(); rectangulo_periodo.rectangle(125, 725, 350, 20); rectangulo_periodo.fill(); drawRectangleSC(rectangulo_periodo, 125, 725, 350, 20); String url_logo = "/Imagenes/itt_logo_opt.jpg"; String absolute_url_logo = getServletContext().getRealPath(url_logo); Image itt_logo = Image.getInstance(absolute_url_logo); String url_logo_bnmx = "/Imagenes/bnmx_color_opt.jpg"; String absolute_url_logo_bnmx = getServletContext().getRealPath(url_logo_bnmx); Image bnmx_logo = Image.getInstance(absolute_url_logo_bnmx); Image Logo_itt = Image.getInstance(itt_logo); Logo_itt.setAbsolutePosition(140f, 640f); preficha.add(Logo_itt); Image Logo_banco = Image.getInstance(bnmx_logo); Logo_banco.setAbsolutePosition(380f, 340f); preficha.add(Logo_banco); PdfContentByte espacio_imagen = writer.getDirectContentUnder(); espacio_imagen.rectangle(255, 635, 85, 80); espacio_imagen.fill(); drawRectangleSC(espacio_imagen, 255, 635, 85, 80); // preficha.add(vacio); preficha.add(vacio); PdfContentByte fechaimpr = writer.getDirectContentUnder(); fechaimpr.rectangle(416, 635, 100, 35); fechaimpr.fill(); drawRectangleSC(fechaimpr, 416, 635, 100, 35); // drawRectangle(fechaimpr, 85, 530, 430, 25); Paragraph fechapdf = new Paragraph("\tFecha de impresin ", FontFactory.getFont("arial", 10, com.itextpdf.text.Font.BOLD)); fechapdf.setAlignment(Element.ALIGN_RIGHT); preficha.add(fechapdf); Paragraph fechapdf_fec = new Paragraph("\t" + fecha_hoy() + " ", FontFactory.getFont("arial", 10, com.itextpdf.text.Font.BOLD)); fechapdf_fec.setAlignment(Element.ALIGN_RIGHT); preficha.add(fechapdf_fec); preficha.add(vacio); Paragraph no_preficha = new Paragraph("Preficha N: " + prefichabd, FontFactory.getFont("arial", 20, Font.BOLD)); no_preficha.setAlignment(Element.ALIGN_CENTER); preficha.add(no_preficha); preficha.add(vacio); // preficha.add(vacio); PdfContentByte rectangulo_preficha_no = writer.getDirectContentUnder(); rectangulo_preficha_no.rectangle(85, 590, 430, 25); rectangulo_preficha_no.fill(); drawRectangleSC(rectangulo_preficha_no, 85, 590, 430, 25); PdfContentByte rectangulo_datos = writer.getDirectContentUnder(); rectangulo_datos.rectangle(85, 500, 430, 80); // rectangulo_datos.rec rectangulo_datos.fill(); drawRectangleSC(rectangulo_datos, 85, 500, 430, 80); ////////////////////////////// Paragraph nombre = new Paragraph( " Nombre: " + nombrebd, FontFactory.getFont("arial", 10, Font.BOLD)); nombre.setAlignment(Element.ALIGN_LEFT); preficha.add(nombre); // preficha.add(vacio); Paragraph apellidos = new Paragraph( " " + apellidosbd, FontFactory.getFont("arial", 10, Font.BOLD)); apellidos.setAlignment(Element.ALIGN_LEFT); preficha.add(apellidos); // preficha.add(vacio); Paragraph CURP = new Paragraph( " CURP: " + curpbd, FontFactory.getFont("arial", 10, Font.BOLD)); CURP.setAlignment(Element.ALIGN_LEFT); preficha.add(CURP); // preficha.add(vacio); Paragraph carrera = new Paragraph( " Carrera Solicitada: " + carrerabd, FontFactory.getFont("arial", 10, Font.BOLD)); carrera.setAlignment(Element.ALIGN_LEFT); preficha.add(carrera); // preficha.add(vacio); Paragraph modalidad = new Paragraph( " Modalidad: " + modalidadbd, FontFactory.getFont("arial", 10, Font.BOLD)); modalidad.setAlignment(Element.ALIGN_LEFT); preficha.add(modalidad); preficha.add(vacio); // preficha.add(vacio); Paragraph formatoBanamex = new Paragraph("FORMATO UNIVERSAL PARA DEPSITOS EN SUCURSALES BANAMEX", FontFactory.getFont("arial", 10, Font.BOLD)); formatoBanamex.setAlignment(Element.ALIGN_CENTER); preficha.add(formatoBanamex); PdfContentByte rectanguloDepositoB = writer.getDirectContentUnder(); rectanguloDepositoB.rectangle(85, 470, 430, 20); rectanguloDepositoB.fill(); drawRectangle(rectanguloDepositoB, 85, 470, 430, 20); PdfContentByte rectanguloPago = writer.getDirectContentUnder(); rectanguloPago.rectangle(85, 280, 430, 190); rectanguloPago.fill(); drawRectangleSC(rectanguloPago, 85, 280, 430, 190); preficha.add(vacio); PdfContentByte rectanguloConcepto = writer.getDirectContentUnder(); rectanguloConcepto.rectangle(150, 425, 295, 35); // rectangulo_datos.rec rectanguloConcepto.fill(); drawRectangleSC(rectanguloConcepto, 150, 425, 295, 35); Paragraph formatoConceptoPre = new Paragraph("CONCEPTO: PAGO DE DERECHO A EXAMEN DE ADMISIN", FontFactory.getFont("arial", 10, Font.BOLD)); formatoConceptoPre.setAlignment(Element.ALIGN_CENTER); preficha.add(formatoConceptoPre); Paragraph fechaEmision = new Paragraph("FECHA DE EMISIN: 18/12/2014", FontFactory.getFont("arial", 10, Font.BOLD)); fechaEmision.setAlignment(Element.ALIGN_CENTER); preficha.add(fechaEmision); preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); preficha.add(vacio); Paragraph importe = new Paragraph("IMPORTE A PAGAR: $1,500.", FontFactory.getFont("arial", 15, Font.BOLD)); importe.setAlignment(Element.ALIGN_CENTER); preficha.add(importe); preficha.add(vacio); preficha.add(vacio); preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); String ref = "44353452342353464765634523434"; Paragraph referencia = new Paragraph( " REFERENCIA (B): " + ref, FontFactory.getFont("arial", 10, Font.BOLD)); referencia.setAlignment(Element.ALIGN_LEFT); preficha.add(referencia); preficha.add(vacio); // Paragraph descrConcepto = new Paragraph("DESCRIPCIN DEL CONCEPTO: CUOTA POR CONCEPTO DE PREINCRIPCIN.", FontFactory.getFont("arial", 10, Font.BOLD)); // descrConcepto.setAlignment(Element.ALIGN_CENTER); // preficha.add(descrConcepto); preficha.add(vacio); preficha.add(vacio); preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); // preficha.add(vacio); Paragraph atencion = new Paragraph("Atencin", FontFactory.getFont("arial", 15, Font.BOLD)); atencion.setAlignment(Element.ALIGN_CENTER); preficha.add(atencion); PdfContentByte rectangulo_atencion = writer.getDirectContentUnder(); rectangulo_atencion.rectangle(245, 229, 100, 25); rectangulo_atencion.fill(); drawRectangle(rectangulo_atencion, 245, 229, 100, 25); PdfContentByte rectangulo_info = writer.getDirectContentUnder(); rectangulo_info.rectangle(85, 94, 430, 100); rectangulo_info.fill(); drawRectangle(rectangulo_info, 85, 94, 430, 120); preficha.add(vacio); preficha.add(vacio); Paragraph informacion = new Paragraph( " Para continuar con el proceso de preinscripcin debers:\n" + " - Realizar el pago para tu examen de admisin con la \"REFERENCIA\" que aparece\n" + " en este documento en cualquier sucursal BANAMEX.\n" + " - Recibir la notificacin en tu correo electrnico y estar al pendiente de \n" + " las notificaciones que sern enviadas al mismo de que el pago ya fue procesado \n" + " para completar tu proceso de preinscripcin.\n", FontFactory.getFont("arial", 10, Font.BOLD)); informacion.setAlignment(Element.ALIGN_LEFT); preficha.add(informacion); // pie // pie // pie // pie // pie preficha.add(vacio); preficha.add(vacio); preficha.addTitle("Preficha"); preficha.addSubject("Instituto Tecnolgico de Toluca"); preficha.addKeywords("Instituto Tecnolgico de Toluca"); preficha.addAuthor("Departamento de Servicios escolares"); preficha.addCreator("Departamento de Servicios escolares"); preficha.close(); preficha.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } } catch (SQLException ex) { Logger.getLogger(PrefichaPDF.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:pdfservlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from www . j a v a 2s.c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResultSet resultSet = null; Statement statement = null; try { Connection connection = ConnectionManager.createConnectionToDB(); String query = "SELECT * FROM employees"; statement = connection.createStatement(); resultSet = statement.executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } response.setContentType("application/pdf"); Document document = new Document(); Font font3 = new Font(Font.FontFamily.TIMES_ROMAN, 8); Font font4 = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD); Font font2 = new Font(Font.FontFamily.COURIER, 10, Font.UNDERLINE); try { PdfWriter.getInstance(document, response.getOutputStream()); document.open(); document.add(new Phrase(new Date().toString() + "\n", font3)); String imageUrl = "http://www.technolinks.in/images/bhel_logo.jpg"; Image image2 = Image.getInstance(new URL(imageUrl)); image2.scaleAbsolute(100f, 100f); image2.setAbsolutePosition(25f, 725f); document.add(image2); document.add(new Phrase( " BHEL Recruitment for Medical Professionals \n ", font3)); document.add(new Phrase("Admit Card for Interview of Medical Professional in BHEL\n", font2)); document.add( new Phrase(" Acknowledgement No :", font3)); document.addCreator("Shivin"); document.addTitle("BHEL"); resultSet.next(); String trade_id = "100003"; do { if (trade_id.matches(resultSet.getString("TRADE"))) break; } while (resultSet.next()); document.add(new Phrase("Post Applied: " + resultSet.getString("TRADE") + "\n")); document.add(new Phrase("Name: " + resultSet.getString("FIRSTNAME") + "\n")); document.add(new Phrase("Father's/Husband's Name:" + resultSet.getString("FATHERNAME"))); document.add(new Phrase("Address: " + resultSet.getString("ADDRESS1") + "\n" + resultSet.getString("ADDRESS2") + "\n" + resultSet.getString("DISTRICT") + resultSet.getString("CITY") + "\n")); document.add(new Phrase("State: " + resultSet.getString("STATE") + "\n")); document.add(new Phrase("Pin: " + resultSet.getString("PIN") + "\n")); document.add(new Phrase("Caste: " + resultSet.getString("CASTE") + "\n")); document.add(new Phrase("Interview Date: " + resultSet.getString("INTERVIEW_DATE") + "\n")); document.add( new Phrase("Interview Time: " + resultSet.getString("INTERVIEW_TIME") + "\n")); document.add( new Phrase("Reporting Time: " + resultSet.getString("REPORTING_TIME") + "\n")); document.add(new Phrase("Interview Venue: " + resultSet.getString("INTERVIEW_VENUE") + "\n")); document.add(new Phrase("Important Instructions: \n", font4)); document.add( new Paragraph("1.You must bring along with you the original documents and 01 selfattested\n" + "photocopy of the following :\n" + "Xth Certificate/ Birth Certificate mentioning Date of Birth\n" + "MBBS Degree Certificate / Marksheets of all year\n" + "PG Diploma / PG Degree / DNB Certificate in relevant discipline\n" + "Medical Council Registration Certificate\n" + "Post Qualification Experience Certificate in support of the experience being claimed\n" + "Certificate for SC/ST in the prescribed format, if applicable\n" + "Certificate for OBC indicating Non Creamy Layer status in the prescribed format, if applicable\n" + "Self Undertaking for Non Creamy Layer status of OBC in the prescribed format, if applicable\n" + "Medical Certificate for Physically Handicapped candidates for their disability from Government Hospital or Medical Board, if applicable.\n" + "Discharge Certificate for ExServicemen\n" + "NOC from the present employer, if applicable\n" + "2. The shortlisted candidates after attending the interviews will be reimbursed train fare to the extent of single AC 2nd class return train fare\n" + "from the address mentioned in the Application form to Interview Centre, by the shortest route subject to submission of rail/bus Ticket\n" + "3. Please ensure that you fulfill all the prescribed job specifications as advertised and produce all the relevant documents thereof as aforesaid (as\n" + "applicable to you), failing which we will not be able to interview you nor reimburse the Travelling Allowance. In case it is found that a\n" + "candidate does not possess the qualification and /or other specification as prescribed in our advertisement, their candidature will be cancelled abinitio\n" + "and no Travelling Allowance will be paid.\n" + "4. You have the option to answer either in English or in Hindi during the Interview. Please note that no change of Interview place and/or date of\n" + "interview will be possible. Also, we will not be able to respond to any individual queries regarding the results of personal Interview.")); document.add(new Phrase("Declaration by the candidate: \n", font4)); document.add(new Paragraph( "I understand that my permission to this test interview is provisional and if it is found at the later date that I do not fulfill the essential eligibility\n" + "criteria regarding qualification, marks, age, caste, Experience etc. as per requirement of the Company, I will be debarred abinitio\n" + "and I will not\n" + "be able to make any claim to the post.")); document.add(new Phrase("DATE:", font2)); document.add(new Phrase("\n")); document.add(new Phrase("PLACE:", font2)); document.add(new Phrase("\n")); /* PdfPTable table2 = new PdfPTable(1); table2.addCell("1."); table2.addCell("2."); table2.addCell("3."); document.add(new Paragraph(" \n\n\n\n \n\n\n\n\n\n")); document.add(new Paragraph(" *Terms and Conditions \n ")); document.add(table2); document.close(); */ } catch (Exception e) { e.printStackTrace(); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ }
From source file:Registration_Tenant.java
private void saveToPdf() { try {//from w w w. ja v a 2 s.c o m String gend = ""; Document doc = new Document(); BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt")); String path = ""; try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } path = sb.toString().trim(); } finally { br.close(); } FileOutputStream fos = new FileOutputStream( path + "\\registration\\" + lastNameTextField.getText().trim() + ", " + firstNameTextField.getText().trim() + "RegistrationResidentForm.pdf"); PdfWriter pdfWriter = PdfWriter.getInstance(doc, fos); PdfReader pdfReader = new PdfReader("RegistrationResidentForm.pdf"); PdfStamper pdfStamper = new PdfStamper(pdfReader, fos); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getOverContent(i); byte[] cc = null; if (file != null) { File thisFile = new File(file); cc = Files.readAllBytes(thisFile.toPath()); } if (cc != null) { Image image1 = Image.getInstance(cc); image1.scaleAbsolute(95, 105); image1.setAbsolutePosition(465f, 635f); content.addImage(image1); } //Text over the existing page BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED); content.beginText(); content.setFontAndSize(bf, 10); //last name content.showTextAligned(PdfContentByte.ALIGN_LEFT, lastNameTextField.getText().trim(), 175, 610, 0); //first name content.showTextAligned(PdfContentByte.ALIGN_LEFT, firstNameTextField.getText().trim(), 325, 610, 0); //middle name content.showTextAligned(PdfContentByte.ALIGN_LEFT, middleNameTextField.getText().trim(), 470, 610, 0); //college content.showTextAligned(PdfContentByte.ALIGN_LEFT, collegeTextField.getText().trim(), 180, 582, 0); //Course and year content.showTextAligned(PdfContentByte.ALIGN_LEFT, courseTextField.getText().trim() + " - " + yearTextField.getText().trim(), 180, 568, 0); //department content.showTextAligned(PdfContentByte.ALIGN_LEFT, departmentTextField.getText().trim(), 400, 582, 0); String g; if (male.isSelected()) { g = "Male";//6 } else { g = "Female";//6 } //Sex content.showTextAligned(PdfContentByte.ALIGN_LEFT, g, 400, 568, 0); //Home address content.showTextAligned(PdfContentByte.ALIGN_LEFT, homeAddressTextArea.getText(), 110, 540, 0); //resident mobile no1 content.showTextAligned(PdfContentByte.ALIGN_LEFT, MobileNumber1.getText().trim(), 187, 485, 0); //resident mobile no2 content.showTextAligned(PdfContentByte.ALIGN_LEFT, MobileNumber2.getText().trim(), 187, 470, 0); //student email content.showTextAligned(PdfContentByte.ALIGN_LEFT, email.getText().trim(), 397, 485, 0); //fathers name content.showTextAligned(PdfContentByte.ALIGN_LEFT, fatherNameTextField.getText().trim(), 110, 443, 0); //fathers area code content.showTextAligned(PdfContentByte.ALIGN_LEFT, fACodeTextField.getText().trim(), 300, 443, 0); //father landline content.showTextAligned(PdfContentByte.ALIGN_LEFT, fphoneNumberTextField.getText().trim(), 355, 443, 0); //father mobile content.showTextAligned(PdfContentByte.ALIGN_LEFT, fMobileNumberTextField.getText().trim(), 490, 443, 0); //father email content.showTextAligned(PdfContentByte.ALIGN_LEFT, fEmailTextField.getText().trim(), 110, 430, 0); //mother name content.showTextAligned(PdfContentByte.ALIGN_LEFT, motherNameTextField.getText().trim(), 110, 402, 0); //mother area code content.showTextAligned(PdfContentByte.ALIGN_LEFT, mACodeTextField.getText().trim(), 300, 402, 0); //mother landline content.showTextAligned(PdfContentByte.ALIGN_LEFT, mphoneNumberTextField.getText().trim(), 355, 402, 0); //mother mobile content.showTextAligned(PdfContentByte.ALIGN_LEFT, mMobileNumberTextField.getText().trim(), 490, 402, 0); //mother email content.showTextAligned(PdfContentByte.ALIGN_LEFT, mEmailTextField.getText().trim(), 110, 387, 0); //guardian name content.showTextAligned(PdfContentByte.ALIGN_LEFT, guardianNameTextField.getText().trim(), 170, 335, 0); //guardian contact number content.showTextAligned(PdfContentByte.ALIGN_LEFT, gContactNumber1.getText().trim(), 470, 335, 0); //guardian address content.showTextAligned(PdfContentByte.ALIGN_LEFT, guardianAddress.getText().trim(), 125, 322, 0); //guardian relation content.showTextAligned(PdfContentByte.ALIGN_LEFT, relationToGuardian.getText().trim(), 170, 307, 0); content.setFontAndSize(bf, 12); //room details content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Room No.: " + roomNumberTextField.getSelectedItem().toString().trim() + " - " + roomTypeTextField.getText().trim(), 355, 235, 0); content.endText(); } pdfStamper.close(); pdfReader.close(); fos.close(); pdfWriter.close(); } catch (DocumentException ex) { // Logger.getLogger(Registration_Tenant.class.getName()).log(Level.SEVERE, null, ex); new MessageDialog().error(this, ex.getMessage()); } catch (FileNotFoundException ex) { // Logger.getLogger(Registration_Tenant.class.getName()).log(Level.SEVERE, null, ex); new MessageDialog().error(this, ex.getMessage()); } catch (IOException ex) { // Logger.getLogger(Registration_Tenant.class.getName()).log(Level.SEVERE, null, ex); new MessageDialog().error(this, ex.getMessage()); } }
From source file:app.logica.gestores.GestorPDF.java
License:Open Source License
/** * Mtodo para crear un PDF a partir de una pantalla. */* w w w . j ava2 s . c o m*/ * @param pantallaAPDF * pantalla que se imprimir en PDF * @return PDF de una captura de la pantalla pasada */ private PDF generarPDF(Node pantallaAPDF) throws Exception { //Se imprime la pantalla en una imagen new Scene((Parent) pantallaAPDF); WritableImage image = pantallaAPDF.snapshot(new SnapshotParameters(), null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos); byte[] imageInByte = baos.toByteArray(); baos.flush(); baos.close(); //Se carga la imagen en un PDF Image imagen = Image.getInstance(imageInByte); Document document = new Document(); ByteArrayOutputStream pdfbaos = new ByteArrayOutputStream(); PdfWriter escritor = PdfWriter.getInstance(document, pdfbaos); document.open(); imagen.setAbsolutePosition(0, 0); imagen.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); document.add(imagen); document.close(); //Se obtiene el archivo PDF byte[] pdfBytes = pdfbaos.toByteArray(); pdfbaos.flush(); escritor.close(); pdfbaos.close(); //Se genera un objeto PDF return (PDF) new PDF().setArchivo(pdfBytes); }
From source file:app.logica.gestores.GestorPDF.java
License:Open Source License
/** * Mtodo para crear un PDF a partir de varias pantalla. *//w w w. j a v a 2 s. c o m * @param pantallaAPDF * pantalla que se imprimir en PDF * @return PDF de una captura de la pantalla pasada */ private PDF generarPDF(ArrayList<Node> pantallasAPDF) throws Exception { Document document = new Document(); ByteArrayOutputStream pdfbaos = new ByteArrayOutputStream(); PdfWriter escritor = PdfWriter.getInstance(document, pdfbaos); document.open(); for (Node pantalla : pantallasAPDF) { new Scene((Parent) pantalla); WritableImage image = pantalla.snapshot(new SnapshotParameters(), null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos); byte[] imageInByte = baos.toByteArray(); baos.flush(); baos.close(); Image imagen = Image.getInstance(imageInByte); imagen.setAbsolutePosition(0, 0); imagen.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); document.add(imagen); document.newPage(); } document.close(); byte[] pdfBytes = pdfbaos.toByteArray(); pdfbaos.flush(); escritor.close(); pdfbaos.close(); return (PDF) new PDF().setArchivo(pdfBytes); }
From source file:avalonscrollmaker20.AnothakScribe.java
License:Open Source License
public void writeToDoc(ArrayList<AnothakScroll> spellList, boolean simpleMode) { // Format content for inserting into a PDF for (int i = 0; i < spellList.size(); i++) { Paragraph spellCode = new Paragraph(spellList.get(i).spellCode, f_code); spellCode.setAlignment(ElementTags.ALIGN_RIGHT); spellCode.setMultipliedLeading(0.5f); spellCode.setIndentationRight(15f); Paragraph spellTitle = new Paragraph(spellList.get(i).spellTitle + "\n", f_title); spellTitle.setAlignment(ElementTags.ALIGN_CENTER); spellTitle.setMultipliedLeading(0.5f); spellTitle.setSpacingAfter(36f); Paragraph spellCircleSchool;/*from w ww . ja v a 2 s .c o m*/ if (spellList.get(i).isPure()) spellCircleSchool = new Paragraph(spellList.get(i).spellCircle.toString() + " Circle\n of " + spellList.get(i).spellOldSchool.toString(), f_schoolPure); else // !spellList.get( i ).isPure() spellCircleSchool = new Paragraph(spellList.get(i).spellCircle.toString() + " Circle\n of " + spellList.get(i).spellOldSchool.toString(), f_school); spellCircleSchool.setAlignment(ElementTags.ALIGN_LEFT); spellCircleSchool.setIndentationLeft(18f); spellCircleSchool.setMultipliedLeading(1.75f); Paragraph sourceKeu = new Paragraph(spellList.get(i).sourceKeu.toString() + "|~", f_keu); sourceKeu.setAlignment(ElementTags.ALIGN_RIGHT); sourceKeu.setIndentationRight(36f); sourceKeu.setMultipliedLeading(1f); Paragraph directionKeu = new Paragraph("", f_keu); directionKeu.setAlignment(ElementTags.ALIGN_RIGHT); directionKeu.setIndentationRight(90f); directionKeu.setMultipliedLeading(0.875f); Paragraph destinationKeu = new Paragraph(spellList.get(i).destinationKeu.toString() + "|~", f_keu); destinationKeu.setAlignment(ElementTags.ALIGN_RIGHT); destinationKeu.setIndentationRight(36f); destinationKeu.setMultipliedLeading(0.625f); Paragraph phraseCommon; Paragraph phraseSymbol; if (spellList.get(i).spellCircle != Circle.SEVENTH && spellList.get(i).spellCircle != Circle.PURE_SEVENTH) { phraseCommon = new Paragraph("", f_phraseCommon); phraseCommon.setSpacingAfter(27f); phraseSymbol = new Paragraph("", f_phraseSymbol); if ((i % 2) <= 0) phraseSymbol.setSpacingAfter(90f); else // ( (i % 2) > 0 ) phraseSymbol.setSpacingAfter(0f); } else { phraseCommon = new Paragraph("", f_phraseCommonBreath); phraseCommon.setSpacingAfter(36f); phraseSymbol = new Paragraph("", f_phraseSymbolBreath); if ((i % 2) <= 0) phraseSymbol.setSpacingAfter(103.5f); else // ( (i % 2) > 0 ) phraseSymbol.setSpacingAfter(0f); } phraseCommon.setAlignment(ElementTags.ALIGN_CENTER); phraseCommon.setMultipliedLeading(1.5f); for (AnothakScroll.Word w : spellList.get(i).liersethPhrase_Common) phraseCommon.add(w.toString() + " "); if (simpleMode) { phraseSymbol.setAlignment(ElementTags.ALIGN_CENTER); phraseSymbol.setSpacingBefore(36f); phraseSymbol.setSpacingAfter(0f); phraseSymbol.setMultipliedLeading(0.75f); } else // not simpleMode { phraseSymbol.setAlignment(ElementTags.ALIGN_CENTER); phraseSymbol.setMultipliedLeading(0.5f); } for (AnothakScroll.Symbol s : spellList.get(i).liersethPhrase_Symbol) { phraseSymbol.add(s.toString()); } // Add content to the document try { if (simpleMode) doc_scrolls.add(phraseSymbol); else { Image tmpImage = null; tmpImage = spellList.get(i).backgroundImageFull; if (tmpImage != null) { if ((i % 2) <= 0) tmpImage.setAbsolutePosition(9f, 405f); else // (i % 2) >= 0 tmpImage.setAbsolutePosition(9f, 9f); doc_scrolls.add(tmpImage); } //doc_scrolls.add( Chunk.NEWLINE ); doc_scrolls.add(spellCode); doc_scrolls.add(spellTitle); // Crap, I hate formatting MultiColumnText mct = new MultiColumnText(108f); mct.addRegularColumns(doc_scrolls.left(), doc_scrolls.right(), 54f, 2); mct.addElement(spellCircleSchool); mct.addElement(sourceKeu); mct.addElement(directionKeu); mct.addElement(destinationKeu); doc_scrolls.add(mct); doc_scrolls.add(new Chunk("\n", new Font(Font.FontFamily.COURIER, 18f, Font.NORMAL))); doc_scrolls.add(phraseCommon); doc_scrolls.add(phraseSymbol); if ((i % 2) > 0) doc_scrolls.newPage(); } } catch (Exception ex) { System.err.println(ex + "\nProgram closing."); System.exit(4); } } // Close the Document doc_scrolls.close(); JOptionPane.showMessageDialog(null, doc_name + " was printed successfully!", "Print Status", JOptionPane.INFORMATION_MESSAGE); }
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] fixBackground(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final byte[] tocTemplate = templateRepository.findOne(pdfTemplate.getTocTemplate().getUrl()); final byte[] modelPageTemplate = templateRepository.findOne(pdfTemplate.getModel().getUrl()); final Image tocBackgroundImage = iTextUtil.getImageFromPdf(tocTemplate); tocBackgroundImage.setAbsolutePosition(0, 0); final Image modelPageBackgroundImage = iTextUtil.getImageFromPdf(modelPageTemplate); modelPageBackgroundImage.setAbsolutePosition(0, 0); final PdfReader reader = new PdfReader(pdf); final PdfStamper stamper = new PdfStamper(reader, bos); final PdfContentByte tocContent = stamper.getUnderContent(tableOfContents.getFirstPageOfToc()); tocContent.addImage(tocBackgroundImage, 612, 0, 0, 792, 0, 0); for (int pageNumber = tableOfContents.getFirstPageOfToc() + 1; pageNumber <= tableOfContents .getLastPageNumberOfModelPages(); pageNumber++) { final PdfContentByte content = stamper.getUnderContent(pageNumber); content.addImage(modelPageBackgroundImage, 612, 0, 0, 792, 0, 0); }//from w w w . j a va 2 s . c o m stamper.close(); reader.close(); return bos.toByteArray(); } }
From source file:bicimotos3hermanos.MainFrom.java
public void toPFD(String out, String in) { try {/* w w w . j a v a2 s. co m*/ //Create Document Object Document convertJpgToPdf = new Document(); //Create PdfWriter for Document to hold physical file PdfWriter.getInstance(convertJpgToPdf, new FileOutputStream(out));//"c:\\java\\ConvertImagetoPDF.pdf" convertJpgToPdf.open(); //Get the input image to Convert to PDF Image convertJpg = Image.getInstance(in); convertJpg.setAbsolutePosition(0f, 260f);//posicion en x,y convertJpg.scalePercent(72, 85);//porcentaje en escala //Add image to Document convertJpgToPdf.add(convertJpg); //Close Document convertJpgToPdf.close(); System.out.println("Successfully Converted JPG to PDF in iText"); } catch (Exception i1) { i1.printStackTrace(); } }
From source file:bouttime.report.bracketsheet.BracketSheetReport.java
License:Open Source License
public static boolean generateReport(Dao dao, List<Group> list, String outputFile, boolean doBoutNumbers, boolean doTimestamp) { if (list.isEmpty()) { return false; }//from w w w.j a v a 2 s. c om // step 1: creation of a document-object Document document = new Document(); try { // step 2: creation of the writer FileOutputStream fos = createOutputFile(outputFile); if (fos == null) { return false; } PdfWriter writer = PdfWriter.getInstance(document, fos); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); String timestamp = ""; if (doTimestamp) { timestamp = DateFormat.getInstance().format(new Date()); } int rv; int i = 0; int size = list.size(); for (Group g : list) { rv = addBracket(cb, dao, g, doBoutNumbers); if (rv != PAGE_ERROR) { // Print the watermark, if necessary boolean doWatermark = false; String gClass = g.getClassification(); String wmValues = dao.getBracketsheetWatermarkValues(); if ((wmValues != null) && !wmValues.isEmpty()) { String[] tokens = wmValues.split(","); for (String s : tokens) { if (s.trim().equalsIgnoreCase(gClass)) { doWatermark = true; break; } } } int rotation = (rv == PAGE_ROUNDROBIN) ? 45 : 135; if (doWatermark) { PdfContentByte ucb = writer.getDirectContentUnder(); BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false); ucb.saveState(); ucb.setColorFill(BaseColor.LIGHT_GRAY); ucb.beginText(); ucb.setFontAndSize(helv, 86); ucb.showTextAligned(Element.ALIGN_CENTER, gClass, document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, rotation); ucb.endText(); ucb.restoreState(); } if (doTimestamp) { rotation -= 45; float width = cb.getPdfWriter().getPageSize().getWidth(); int x = (rv == PAGE_ROUNDROBIN) ? 15 : (int) (width - 15); int y = 15; BracketSheetUtil.drawTimestamp(cb, null, x, y, 10, timestamp, rotation); } // If not doing bout numbers, this is an 'award' type of // bracket. So print an image/logo, if configured. if (!doBoutNumbers && (dao.getBracketsheetAwardImage() != null) && !dao.getBracketsheetAwardImage().isEmpty()) { Image image = Image.getInstance(Image.getInstance(dao.getBracketsheetAwardImage())); image.setRotationDegrees((rv == PAGE_ROUNDROBIN) ? 0 : 90); PositionOnPage positionOnPage = dao.getBracketsheetAwardImagePosition(); if (PositionOnPage.UPPER_RIGHT == positionOnPage) { float x = (rv == PAGE_ROUNDROBIN) ? document.getPageSize().getWidth() - 10 - image.getWidth() : 10; float y = document.getPageSize().getHeight() - 10 - image.getHeight(); image.setAbsolutePosition(x, y); cb.addImage(image); } else if (PositionOnPage.CENTER == positionOnPage) { // put the image in the background, in the middle of the page PdfContentByte ucb = writer.getDirectContentUnder(); float pageX = document.getPageSize().getWidth() / 2; float pageY = document.getPageSize().getHeight() / 2; float imageX = image.getWidth() / 2; float imageY = image.getHeight() / 2; image.setAbsolutePosition(pageX - imageX, pageY - imageY); ucb.addImage(image); } } if (++i < size) { document.newPage(); } } } } catch (DocumentException de) { logger.error("Document Exception", de); return false; } catch (IOException ioe) { logger.error("IO Exception", ioe); return false; } // step 5: we close the document document.close(); return true; }